EMZETT.
Login

Switch Statement

In short: A multi-way branch that checks a value against several possible case values — more readable than a long chain of if...else if.

In more detail: Classic syntax needs a break; at the end of every case, otherwise execution falls through into the next case (“fallthrough”). Newer Java versions (from 14) additionally allow the more compact arrow syntax case X -> ... with no fallthrough risk.

switch (day) {
    case 1 -> System.out.println("Monday");
    case 2 -> System.out.println("Tuesday");
    default -> System.out.println("Unknown");
}

In Depth

// Classic syntax with fallthrough risk:
switch (day) {
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
        System.out.println("Weekday");
        break; // without this break, case 6 would also be printed
    case 6:
    case 7:
        System.out.println("Weekend");
        break;
    default:
        System.out.println("Invalid day");
}
 
// Modern arrow syntax (from Java 14) - no fallthrough possible:
String kind = switch (day) {
    case 1, 2, 3, 4, 5 -> "Weekday";
    case 6, 7 -> "Weekend";
    default -> "Invalid day";
};

With the classic case X: syntax, execution continues into the NEXT case with no break (“fallthrough”) — this is sometimes deliberately intended (as above, to map several values to the same result), but usually a source of error when the break is simply forgotten. The newer arrow syntax (case X ->) solves this problem structurally: every case automatically ends after its statement, a fallthrough is no longer syntactically possible at all. Additionally, switch can be used directly as an expression in the new form (see kind = switch (...) above) and, via yield, can even have more complex blocks return a value.

switch works with int/char/enum types, String (since Java 7), as well as newer record/pattern-matching constructs — but not with double/float/boolean.

See also: if Statement, Break/Continue