Construction. The switch expression on enums

[comp1110-76]

switch is a control structure, like if and while. In contrast to these two, however, switch can also be used as an expression form, which means it can be used as the right-hand side of an assignment. For example:

int daysInMonth(Month m, boolean isLeapYear) { int days = switch (m) { case JANUARY -> 31; case FEBRUARY -> { if (isLeapYear) { yield 29; } else { yield 28; } } case MARCH -> 31; case APRIL -> 30; case MAY -> 31; case JUNE -> 30; case JULY -> 31; case AUGUST -> 31; case SEPTEMBER -> 30; case OCTOBER -> 31; case NOVEMBER -> 30; case DECEMBER -> 31; }; // Note the semicolon here return days; }

In this case, it is important that each case of the switch expression returns a value of a suitable type. If you need more complicated logic for a case, you can have a code block enclosed in curly braces, where the special yield statement works like a sort of local return statement.

This form is not really important for this course, but you may encounter it in newer Java code.

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