Java Enumeration

Profile picture for user arilio666

In Java, an Enumeration is a type of object that represents a fixed set of values.  An Enumeration can define a set of constants that can be used throughout a program.

Enum can be used in a period with repeated data usage such as years, colors, etc. Let us see how we can declare an enum, use it in variables, and iterate it.

Enum Creation:

  • With the help of the enum keyword, we can create an enum followed by the name of our choice.
  • With this specified name, we will access the contents inside the enum.
enum characterNames {
        JohnWick, Naruto, Itachi, Eren
    }
  • The general convention of using enum data is uppercase; however, it is unimportant.
  • Here we created enum characterNames and provided some names within.
  • Let us see how we can store and print this in a variable.
    enum characterNames {
        JohnWick, Naruto, Itachi, Eren
    }
    public static void main(String[] args) {
        characterNames eren = characterNames.Eren;
        System.out.println(eren);
    }
}
  • Inside the main method, we can access characterNames without class object creation.
  • Then we store in a variable eren with characterNames as the return type.

Output:

Eren
  • We can see Eren has been printed from the enum.
public static void main(String[] args) {
        characterNames eren = characterNames.Eren;
        System.out.println(eren.ordinal());
    }


Output:

3
  • Using ordinal can return the position number it is situated in the enum.

Loop Enum:

  • Let us see how we can loop an enum using advanced for  loop.
{
        for (characterNames allNames : characterNames.values()) {
            System.out.println(allNames);
        }
    }
  • Here using the advanced loop, we have used the characterNames, and with the help of method values, we iterated through the entire enum and stored it in allNames.
  • Once we print allNames, we can see all the names listed inside the enum.

Output:

JohnWick
Naruto
Itachi
Eren
Tags