Enums in Java (Part 9)

Pre-requisites:-  Switch StatementEnhanced-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:-
 enum Enum_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 enum  
 enum Color {  
      RED, YELLOW, BLUE, GREEN;  
 }  
   
 public class MyClass {  
      public static void main(String args[]) {  
           // accessing blue element  
           Color color = Color.BLUE;  
           System.out.println(color);  
      }  
 }  
Output:-
 BLUE  



2. Enum in Switch statement

Enums are widely used in switch statements.

Eg:-
 enum Level {  
      LOW, MEDIUM, HIGH;  
 }  
   
 public class MyClass {  
      public static void main(String[] args) {  
           Level level = Level.HIGH;  
   
           switch (level) {  
           case LOW:  
                System.out.println("Low level");  
                break;  
           case MEDIUM:  
                System.out.println("Medium level");  
                break;  
           case HIGH:  
                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:-
 enum Level {  
      LOW, MEDIUM, HIGH; 
 }  
 public class MyClass {  
      public static void main(String[] args) {  
           for (Level i : Level.values()) {  
                System.out.println(i);  
           }  
      }  
 }  
Output:-
 LOW  
 MEDIUM  
 HIGH  



< Previous Next >