Construction. The switch statement on enums

[comp1110-2K]

Java provides a convenient way to perform different actions depending on an enum value: the switch statement.

void printShortMonthName(Month m) { switch (m) { case JANUARY -> IO.println("Jan"); case FEBRUARY -> IO.println("Feb"); case MARCH -> IO.println("Mar"); case APRIL -> IO.println("Apr"); case MAY -> IO.println("May"); case JUNE -> IO.println("Jun"); case JULY -> IO.println("Jul"); case AUGUST -> IO.println("Aug"); case SEPTEMBER -> IO.println("Sep"); case OCTOBER -> IO.println("Oct"); case NOVEMBER -> IO.println("Nov"); case DECEMBER -> IO.println("Dec"); } }

The switch examines the value of g. Each line specifies what to do for one possible value. If m is Month.MARCH, for example, the program prints "Mar".

Notice that inside the switch we write the constants without the Month. prefix. Java already knows that m has type Month, so it knows which constants we mean.

bars magnifying-glass caret-down plus minus arrow-right xmark