Just like how we used enums for comparison in ‘if’ statement, we can also use enums in switch case as follows.
package com.ibytecode.enums; public class PizzaEnumSwitch { enum PizzaSize { SMALL, MEDIUM, LARGE }; PizzaSize size; public static void main(String[] args) { PizzaEnumSwitch pizza = new PizzaEnumSwitch(); pizza.size = PizzaSize.LARGE; switch (pizza.size) { case SMALL: System.out.println("Making SMALL Pizza"); break; case MEDIUM: System.out.println("Making MEDIUM Pizza"); break; case LARGE: System.out.println("Making LARGE Pizza"); break; } } }
The enum variable is specified as switch expression and all the case constants should be values from the specified enum.
The case constants should be specified without the enum type qualifier (i.e.) we should NOT specify as PizzaSize.SMALL but instead just use SMALL because the type is already identified from the switch expression.