Java-Switch with Enumeration

Switch with Enumeration

An enumeration value can also be used to control a switch statement. Of course, all of the case statements must use constants from the same enum as that used by the switch expression. For example, in the following program, notice that in the case statements, the names of the enumeration constants are used without being qualified by their enumeration type name. That is, ‘Apple’, not ‘Fruits.Apple’, is used. This is because the type of the enumeration in the switch expression has already implicitly specified the enum type of the case constants. There is no need to qualify the constants in the case statements with their enum type name.

Program

0

Program Source

enum Fruits {
    
    Apple, Banana, Cherry, Date, Elderberry
}

public class Javaapp {

    public static void main(String[] args) {
        
        Fruits fru = Fruits.Cherry;
        
        switch(fru)
        {
            case Apple :
                System.out.println("Apple");
                break ;
            case Banana :
                System.out.println("Banana");
                break ; 
            case Cherry :
                System.out.println("Cherry");
                break ;
            case Date :
                System.out.println("Date");
                break ;
            case Elderberry :
                System.out.println("Elderberry");
                break ;      
        }
    }
}

Leave a Comment