Java Enums
An enum is a special “class” that represents a group of constants (cannot be changed, like final variables).
Example
enum Speed{ LOW, MEDIUM, HIGH }
The enum constants can be accessed with the dot syntax:
Speed myVar = Speed.HIGH;
Enum is the short form of “enumerations” , which means “specifically listed”.
Example
enum Speed{ LOW, MEDIUM, HIGH } public class EnumClass { public static void main (String args[]){ Speed myVar = Speed.HIGH; System.out.println(myVar); } }
Output
HIGH
Enum Inside a Class
We can have an enum inside a class.
Example
public class EnumClass { enum Speed{ LOW, MEDIUM, HIGH } public static void main (String args[]){ Speed myVar = Speed.MEDIUM; System.out.println(myVar); } }
Output
MEDIUM
Enum in a Switch Statement
Enums are often used in switch statements to check for the corresponding case values:
Example
public class EnumClass { enum Speed{ LOW, MEDIUM, HIGH } public static void main (String args[]){ Speed myVar = Speed.MEDIUM; switch (myVar){ case LOW: System.out.println("Low speed"); break; case MEDIUM: System.out.println("Medium speed"); break; case HIGH: System.out.println("High level"); break; } }
Output
Medium speed
Loop through an Enum
The enum type has values() method, which returns an array of all enum constants.. This method is useful when we want to loop through constants of an enum.
Example
In the below example, we use for loop to loop through the constants.
public class EnumClass { enum Speed{ LOW, MEDIUM, HIGH } public static void main (String args[]){ for(Speed myVar: Speed.values()) { System.out.println(myVar); } } }
Output
LOW MEDIUM HIGH
Enums vs. Classes
Why and When to use Enums?
We use Enums when we use constant values such as month, days, decks of cards, colors etc.