Enumeration in Java


Java enums (declared using the enum keyword) are shorthand syntax for sizable quantities of constants of a single class. Enum can be considered to be syntax sugar for a sealed class that is instantiated only a number of times known at compile-time to define a set of constants. A simple enum to list the different seasons would be declared as follows:

Example :
   public enum GameLevel
   {
       LOW,
       MEDIUM,
       HIGH,
   }

Source Code

//Enumeration in Java
public class enumDemo {
    enum GameLevel {
        LOW,
        MEDIUM,
        HIGH
    }
    public static void main(String[] args) {
        //Assign Enum Variable
        GameLevel a=GameLevel.HIGH;
        System.out.println(a);
 
        //Use Enum in Switch
        switch(a) {
            case LOW:
                System.out.println("Low level");
                break;
            case MEDIUM:
                System.out.println("Medium level");
                break;
            case HIGH:
                System.out.println("High level");
                break;
        }
 
        //Enum by loop
        for (GameLevel level : GameLevel.values()) {
            System.out.println(level);
        }
 
    }
}
 

Output

HIGH
High level
LOW
MEDIUM
HIGH
To download raw file Click Here

Basic Programs