Using Enums in switch case

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 {

	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");
		case MEDIUM:
			System.out.println("Making MEDIUM Pizza");
		case LARGE:
			System.out.println("Making LARGE Pizza");

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.

Leave a Comment