Last week, I wrote about the four forms of switch in Java. I explained that a switch expression without fallthrough is my favourite, and that I would show you how to combine one with an enumerated type (enum).

Enums

I have previously written about enums in JavaScript. Regardless of the language, an enum is a set of named constants. Instead of relying on magic values, you can use an enum to define a set of known values. This makes your code more predictable and less error-prone.

Here’s the switch expression without fallthrough that we looked at last week. Instead of assigning the day variable to a string, let’s examine how we can use an enum to make the switch expression safer.

String day = "Monday";

int numLetters = switch (day) {
case "Monday" -> {
System.out.println("It's Monday!");
yield 6;
}
case "Friday", "Sunday" -> 6;
case "Tuesday" -> 7;
case "Thursday", "Saturday" -> 8;
case "Wednesday" -> 9;
default -> -1;
};

System.out.println(numLetters);

Switch expressions and enums

In a file called SwitchEnumTest.java, let’s declare a Day enum. By convention, the enum constants should be uppercase.

enum Day {SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY}

In the same file, let’s declare the public SwitchEnumTest class. In the body of the main() method, we’ll declare the day variable and assign it to Day.MONDAY. Because the variable is of type Day, the compiler guarantees that it can only be assigned to one of the enum constants (or null). This means we don’t need a default case clause, because the switch expression covers all possible input values.

Note that the case labels have to be the unqualified names of the enum constants, i.e. MONDAY instead of Day.MONDAY. This is nice because it means less typing, but it’s important to understand that it is a syntax error to use the fully qualified name.

public class SwitchEnumTest {
public static void main(String[] args) {
Day day = Day.MONDAY;

int numLetters = switch (day) {
case MONDAY -> {
System.out.println("It's Monday!");
yield 6;
}
case FRIDAY, SUNDAY -> 6;
case TUESDAY -> 7;
case THURSDAY, SATURDAY -> 8;
case WEDNESDAY -> 9;
};

System.out.println(numLetters);
}
}

Wrapping up

So there you have it: switch expressions and enums, a beautiful combination. Enums can be used with all four forms of switch, but I think they go particularly well with switch expressions where each branch computes the value for a variable assignment, as Horstmann phrases it in Core Java.