Enums in switch

Classic switch and switch Expressions

Example

A switch expression over an enum must cover every constant (or have default). If someone adds a new constant later, the compiler points to every switch that needs updating.

public class Main {
    enum Day { MON, TUE, WED, THU, FRI, SAT, SUN }

    static String type(Day d) {
        return switch (d) {
            case SAT, SUN -> "Weekend";
            case MON, TUE, WED, THU, FRI -> "Weekday";
        };
    }

    public static void main(String[] args) {
        for (Day d : Day.values()) {
            System.out.print(d + "=" + type(d) + " ");
        }
        System.out.println();

        Day today = Day.FRI;
        switch (today) {                 // classic switch: no Day. prefix in case labels
            case FRI:
                System.out.println("Deploy freeze starts");
                break;
            default:
                System.out.println("Normal day");
        }
    }
}

Output

MON=Weekday TUE=Weekday WED=Weekday THU=Weekday FRI=Weekday SAT=Weekend SUN=Weekend 
Deploy freeze starts