Enums in Java (Part 9)
Pre-requisites:- Switch Statement , Enhanced-for Loop
Java Enums
An enum is a special class that represents a group of Constants. Enum is short for Enumeration which means specifically listed.
For example the 4 suits in a deck of playing cards may be 4 enums named Club, Diamond, Heart, and Spade, belonging to an enumerated type named Suit.
Declaring an Enum
To create an enum , use the enum keyword, and separate the constants with a comma. Note that they should be in uppercase letters:
Syntax:-
enumEnum_Name{//elements(Constants) in UpperCase letters}
1. Enum Inside / Outside Class
Enum can be declared inside or outside a class , the rules for declaring both of the is same. Whenever an enum element is to be accessed , state the enum name first then " . " and followed by element name.
Eg:-
//declaring an enumenumColor{RED, YELLOW, BLUE, GREEN;} public class MyClass{ public static void main(String args[]) {// accessing blue elementColorcolor= Color.BLUE; System.out.println(color); } }
Output:-
BLUE
2. Enum in Switch statement
Enums are widely used in switch statements.
Eg:-
enumLevel{LOW, MEDIUM, HIGH;} public classMyClass{ public static void main(String[] args) { Levellevel= Level.HIGH; switch (level) { caseLOW: System.out.println("Low level"); break; caseMEDIUM: System.out.println("Medium level"); break; caseHIGH: System.out.println("High level"); break; } } }
Output:-
High level
3. Enum in Loops
Enums can also be used in loops. Here we are using enhanced-for loop. An enum method values( ) returns an array of all enum constants.
Eg:-
enumLevel{LOW, MEDIUM, HIGH; } public classMyClass{ public static void main(String[] args) { for (Leveli:Level.values()) { System.out.println(i); } } }
Output:-
LOW
MEDIUM
HIGH

