Java Switch

Classic switch

Java
int day = 3;

switch (day) {
    case 1:
        System.out.println("Sunday");
        break;
    case 2:
        System.out.println("Monday");
        break;
    case 3:
        System.out.println("Tuesday");
        break;
    default:
        System.out.println("Other day");
}

break is mandatory — without it execution falls through into the next case. That is occasionally useful for grouping:

Java
switch (day) {
    case 6:
    case 7:
        System.out.println("Weekend");
        break;
    default:
        System.out.println("Weekday");
}

Switch expressions (Java 14+)

The modern form: arrow syntax, no fall-through, and it returns a value.

Java
String name = switch (day) {
    case 1 -> "Sunday";
    case 2 -> "Monday";
    case 3 -> "Tuesday";
    case 6, 7 -> "Weekend";
    default -> "Other";
};

System.out.println(name);

Much safer — no forgotten break, and the compiler checks that every case is covered when switching over an enum.

For a multi-statement branch, use a block with yield:

Java
int size = switch (category) {
    case "small" -> 1;
    case "large" -> {
        System.out.println("Large item selected");
        yield 3;
    }
    default -> 0;
};

Switching on strings and enums

Java
switch (status) {
    case "new"     -> System.out.println("Awaiting payment");
    case "paid"    -> System.out.println("Payment received");
    case "shipped" -> System.out.println("On the way");
    default        -> System.out.println("Unknown");
}

When switching over an enum with arrow syntax and no default, the compiler will error if you miss a constant — a genuinely valuable safety net when someone adds a new enum value later.