JVM Knowledge

In addition to the general rules for switch blocks (§14.11.1), there are further rules for switch blocks in switch statements.

An enhanced switch statement is one where either (i) the type of the selector expression is not char, byte, short, int, Character, Byte, Short, Integer, String, or an enum type, or (ii) there is a case pattern or null literal associated with the switch block.

All of the following must be true for the switch block of a switch statement, or a compile-time error occurs:

  • Every switch rule expression in the switch block is a statement expression (§14.8).

    switch statements differ from switch expressions in terms of which expressions may appear to the right of an arrow (->) in the switch block, that is, which expressions may be used as switch rule expressions. In a switch statement, only a statement expression may be used as a switch rule expression, but in a switch expression, any expression may be used (§15.28.1).

  • If the switch statement is an enhanced switch statement, then it must be exhaustive (§14.11.1.1).

Prior to Java SE 21, switch statements (and switch expressions) were limited in two ways: (i) the type of the selector expression was restricted to either an integral type (excluding long), an enum type, or String and (ii) no case null labels were supported. Moreover, unlike switch expressions, switch statements did not have to be exhaustive. This is often the cause of difficult-to-detect bugs, where no switch label applies and the switch statement will silently do nothing. For example:

enum E { A, B, C }
E e = ...;
switch (e) {
   case A -> System.out.println("A");
   case B -> System.out.println("B");
   // No case for C!
}

In Java SE 21, in addition to supporting case patterns, the two limitations of switch statements (and switch expressions) listed above were relaxed to (i) allow a selector expression of any reference type, and (ii) to allow a case label with a null literal. The designers of the Java programming language also decided that enhanced switch statements should align with switch expressions and be required to be exhaustive. This is often achieved with the addition of a trivial default label. For example, the following enhanced switch statement is not exhaustive:

Object o = ...;
switch (o) {    // Error - non-exhaustive switch!
    case String s -> System.out.println("A string!");
}

but it can easily be made exhaustive:

Object o = ...;
switch (o) {
    case String s -> System.out.println("A string!");
    default -> {}
}

For compatibility reasons, switch statements that are not enhanced switch statements are not required to be exhaustive.