tutorialcup
Enumerations in Java
Enum in Java is the short form of Enumeration. The Java Enum class defines a list of constants whose values we cannot change. It is similar to the final variable. We always define the Enum constants in the upper case. In this article, we will see how to enumerate in Java.
Syntax of declaring an Enum (Enumeration)
To declare an enum we must use the enum keyword followed by the variable. Inside the curly braces, we declare the constants separated by a comma.
enum Speed {
SLOW, MEDIUM, FAST
}
Speed - represents the Enum variable name
The values inside the curly braces represent the Enum constants.
Features of Enum (Enumeration)
- We must always define the enum constants using upper case
- We can declare an enum either inside or outside the class
- Enum is a class and every constant is an object of an enum type.
- We can declare fields and methods inside an enum
- Each enum constant is separated by a comma and should end with a semicolon if an enum contains methods as well.
Accessing Enum constants in Java
We can access enum constants in 2 different ways:
- Creating an enum variable: We can create an enum variable by assigning the enum constant to it. We can use this variable to print the value.
enum Speed {
SLOW, MEDIUM, FAST
}
Speed s = Speed.MEDIUM;
System.out.println(d);
- Using enum name: We can directly access the constant using the enum name.
enum Speed {
SLOW, MEDIUM, FAST
}
System.out.println(Speed.SLOW);
Using
Enumerations in Java
Enum in Java is the short form of Enumeration. The Java Enum class defines a list of constants whose values we cannot change. It is similar to the final variable. We always define the Enum constants in the upper case. In this article, we will see how to enumerate in Java.
Syntax of declaring an Enum (Enumeration)
To declare an enum we must use the enum keyword followed by the variable. Inside the curly braces, we declare the constants separated by a comma.
enum Speed {
SLOW, MEDIUM, FAST
}
Speed - represents the Enum variable name
The values inside the curly braces represent the Enum constants.
Features of Enum (Enumeration)
- We must always define the enum constants using upper case
- We can declare an enum either inside or outside the class
- Enum is a class and every constant is an object of an enum type.
- We can declare fields and methods inside an enum
- Each enum constant is separated by a comma and should end with a semicolon if an enum contains methods as well.
Accessing Enum constants in Java
We can access enum constants in 2 different ways:
- Creating an enum variable: We can create an enum variable by assigning the enum constant to it. We can use this variable to print the value.
enum Speed {
SLOW, MEDIUM, FAST
}
Speed s = Speed.MEDIUM;
System.out.println(d);
- Using enum name: We can directly access the constant using the enum name.
enum Speed {
SLOW, MEDIUM, FAST
}
System.out.println(Speed.SLOW);
Using