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,
   }

This program demonstrates the use of enums in Java.

  • The enumDemo class defines an enum named GameLevel with three values: LOW, MEDIUM, and HIGH.
  • In the main method, an enum variable a is assigned the value GameLevel.HIGH. The value of a is then printed to the console.
  • Next, the switch statement is used with the a variable. Depending on the value of a, the appropriate case is executed, and the corresponding message is printed to the console.
  • Finally, a loop is used to iterate over all values of the GameLevel enum, and each value is printed to the console. The values() method returns an array of all values of the enum, which can be used for iteration.

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