An enum is a special type of data type which is basically a collection (set) of constants.
Internal Implementation of enum
Enum declaration
Use of Enum in Switch-Case Statements
Here is the example to demonstrate the use of enums in switch-case statements.
public enum Directions{
EAST,
WEST,
NORTH,
SOUTH
}
public class EnumDemo
{
Directions dir;
public EnumDemo(Directions dir) {
this.dir = dir;
}
public void getMyDirection() {
switch (dir) {
case EAST:
System.out.println(“In East Direction”);
break;
case WEST:
System.out.println(“In West Direction”);
break;
case NORTH:
System.out.println(“In North Direction”);
break;
default:
System.out.println(“In South Direction”);
break;
}
}
public static void main(String[] args) {
EnumDemo obj1 = new EnumDemo(Directions.EAST);
obj1.getMyDirection();
EnumDemo obj2 = new EnumDemo(Directions.SOUTH);
obj2.getMyDirection();
}
}
Output:
In East Direction
In South Direction
Enum Inheritance
Enum methods
How to iterate through an Enum variable
class EnumDemo
{
public static void main(String[] args) {
for (Directions dir : Directions.values()) {
System.out.println(dir);
}
}
}
This code would display all the four constants.
Java enum features
Enum constructor