JVM Knowledge

The body of both a switch statement and a switch expression (§15.28) is called a switch block. This subsection presents general rules which apply to all switch blocks, whether they appear in switch statements or switch expressions. Other subsections present additional rules which apply either to switch blocks in switch statements (§14.11.2) or to switch blocks in switch expressions (§15.28.1).

SwitchBlock:
  { SwitchRule {SwitchRule} }
  { {SwitchBlockStatementGroup} {SwitchLabel :} }

SwitchRule:
  SwitchLabel -> Expression ;
  SwitchLabel -> Block
  SwitchLabel -> ThrowStatement

SwitchBlockStatementGroup:
  SwitchLabel : {SwitchLabel :} BlockStatements

SwitchLabel:
  case CaseConstant {, CaseConstant}
  case null [, default]
  case CasePattern {, CasePattern} [Guard]
  default

CaseConstant:
  ConditionalExpression

CasePattern:
  Pattern

Guard:
  when Expression

A switch block can consist of either:

  • Switch rules, which use -> to introduce either a switch rule expression, a switch rule block, or a switch rule throw statement; or
  • Switch labeled statement groups, which use : to introduce switch labeled block statements.

Every switch rule and switch labeled statement group starts with a switch label, which is either a case label or a default label. Multiple switch labels are permitted for a switch labeled statement group.

A case label has either a (non-empty) list of case constants, a null literal, or a (non-empty) list of case patterns.

Every case constant must be either a constant expression (§15.29), or the name of an enum constant (§8.9.1), otherwise a compile-time error occurs.

A case label with a null literal may have an optional default.

A case label with case patterns may have an optional when expression, known as a guard, which represents a further test on values that match the patterns. A case label is said to be unguarded if either (i) it has no guard, or (ii) it has a guard that is a constant expression (§15.29) with value true; and guarded otherwise.

It is a compile-time error for a case label to have more than one case pattern and declare any pattern variables (other than those declared by a guard associated with the case label).

If a case label with more than one case pattern could declare pattern variables, then it would not be clear which variables would be initialized if the case label were to apply. For example:

Object obj = ...;
switch (obj) {
  case Integer i, Boolean b -> {
    ...       // Error! Is i or b initialized?
  }
  ...
}

Even if only one of the case patterns declares a pattern variable, it would still not be clear whether the variable was initialized or not; for example:

Object obj = ...;
switch (obj) {
  case Integer i, Boolean _ -> {
    ...       // Error! Is i initialized?
  }
  ...
}

The following does not result in a compile-time error:

Object obj = ...;
switch (obj) {
  case Integer _, Boolean _ -> {
    ...       // Matches both an Integer and a Boolean
  }
  ...
}

Switch labels and their case constants, null literals, and case patterns are said to be associated with the switch block.

For a given switch block both of the following must be true, otherwise a compile-time error occurs:

  • No two of the case constants associated with a switch block may have the same value.
  • No more than one null literal may be associated with a switch block.
  • No more than one default label may be associated with a switch block.

A guard associated with a case label must satisfy all of the following conditions, otherwise a compile-time error occurs:

  • A guard must have type boolean or Boolean.
  • Any local variable, formal parameter, or exception parameter used but not declared in a guard must either be final or effectively final (§4.12.4).
  • Any blank final variable used but not declared in a guard must be definitely assigned (§16 (Definite Assignment)) before the guard.
  • A guard cannot be a constant expression (§15.29) with the value false.

The switch block of a switch statement or a switch expression is switch compatible with the type of the selector expression, T, if all of the following are true:

  • If a null literal is associated with the switch block, then T is a reference type.
  • For every case constant associated with the switch block that names an enum constant, the type of the case constant is assignment compatible with T (§5.2).
  • For each case constant associated with the switch block that is a constant expression, the constant is assignment compatible with T, and T is one of char, byte, short, int, Character, Byte, Short, Integer, or String.
  • Every pattern p associated with the switch block is applicable at type T (§14.30.3).

Switch blocks are not designed to work with the types boolean, long, float, and double. The selector expression of a switch statement or switch expression can not have one of these types.

The switch block of a switch statement or a switch expression must be switch compatible with the type of the selector expression, or a compile-time error occurs.

A switch label in a switch block is said to be dominated if for every value that it applies to, it can be determined that one of the preceding switch labels would also apply. It is a compile-time error if any switch label in a switch block is dominated. The rules for determining whether a switch label is dominated are as follows:

  • A case label with a case pattern q is dominated if there is a preceding unguarded case label in the switch block with a case pattern p, and p dominates q (§14.30.3).

    The definition of one pattern dominating another pattern is based on types. For example, the type pattern Object o dominates the type pattern String s, and so the following results in a compile-time error:

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

    A guarded case label with a case pattern is dominated by a case label with the same pattern but without the guard. For example, the following results in a compile-time error:

    String str = ...;
    switch (str) {
        case String s ->
            System.out.println("A string");
        case String s when s.length() == 2 ->  // Error!
            System.out.println("Two character string");
        ...
    }
    

    On the other hand, a guarded case label with a case pattern is not considered to dominate an unguarded case label with the same case pattern. This allows the following common pattern programming style:

    Integer j = ...;
    switch (j) {
        case Integer i when i <= 0 ->
            System.out.println("Less than or equal to zero");
        case Integer i ->
            System.out.println("An integer");
    }
    

    The only exception is where the guard is a constant expression that has the value true, for example:

    Integer j = ...;
    switch (j) {
        case Integer i when true ->            // Ok
            System.out.println("An integer");
        case Integer i ->                      // Error!
            System.out.println("An integer");
    }
    

    A case label with more than one case pattern is dominated if any one of these patterns is dominated by a pattern that appears as a case pattern in a preceding unguarded case label, and so the following results in a compile-time error (as the type pattern Integer _ is dominated by the type pattern Number _):

        Object obj = ...
        switch (obj) {
          case Number _ ->
            System.out.println("A Number");
          case Integer _, String _ ->       // Error - dominated!
            System.out.println("An Integer or a String");
          ...
        }
    
  • A case label with a case constant c is dominated if one of the following holds:

    • c is a constant expression of a primitive type S, and there is a preceding case label in the switch block with an unguarded case pattern p, where p is unconditional for the wrapper class of S.
    • c is a constant expression of a reference type T, and there is a preceding case label in the switch block with an unguarded case pattern p, where p is unconditional for the type T.
    • c names an enum constant of enum class E, and there is a preceding case label in the switch block with an unguarded case pattern p, where p is unconditional for the type E.

    For example, a case label with an Integer type pattern dominates a case label with an integer literal:

    Integer j = ...;
    switch (j) {
        case Integer i ->
            System.out.println("An integer");
        case 42 ->                              // Error - dominated!
            System.out.println("42!");
    }
    
  • A default label or a case null, default label is dominated if there is a preceding unguarded case label in the switch block with a case pattern p where p is unconditional for the type of the selector expression (§14.30.3).

    A case label with a case pattern that is unconditional for the type of the selector expression will, as the name suggests, match every value and so behave like a default label. A switch block can not have more than one switch label that acts like a default.

It is a compile-time error if there is a case label with n (n>1) case patterns p_1, ..., p_n in a switch block where one of the patterns p_i (1≤i<n) dominates another of the patterns p_j (i<j≤n).

It is a compile-time error if any of the following holds:

  • There is a default label in the switch block that precedes a case label with case patterns.
  • There is a default label in the switch block that precedes a case label with a null literal.
  • There is a case null, default label in the switch block followed by any other switch label.

If used, a default label should come last in a switch block.

For compatibility reasons, a default label may appear before case labels that do not have a null literal or case patterns.

int i = ...;
switch(i) {
    default ->
        System.out.println("Some other integer");
    case 42 -> // allowed
        System.out.println("42");
}

If used, a case null, default label should come last in a switch block.

It is a compile-time error if, in a switch block that consists of switch labeled statement groups, a statement is labeled with a case label that declares one or more pattern variables (§6.3.3), and either:

  • An immediately preceding statement in the switch block can complete normally (§14.22), or
  • The statement is labeled with more than one switch label.

The first condition prevents a statement group from "falling through" to another statement group without initializing pattern variables. For example, were the statement labeled by case Integer i reachable from the preceding statement group, the pattern variable i would not have been initialized:

Object o = "Hello";
switch (o) {
    case String s:
        System.out.println("String: " + s );  // No break!
    case Integer i:
        System.out.println(i + 1);            // Error! Can be reached
                                              // without matching the
                                              // pattern `Integer i`
    default:
}

Switch blocks consisting of switch label statement groups allow multiple labels to apply to a statement group. The second condition prevents a statement group from being executed based on one label without initializing the pattern variables of another label. For example:

Object o = "Hello World";
switch (o) {
    case String s:
    case Integer i:
        System.out.println(i + 1);  // Error! Can be reached
                                    // without matching the
                                    // pattern `Integer i`
    default:
}
Object obj = null;
switch (obj) {
    case null:
    case String s:
        System.out.println(s);      // Error! Can be reached
                                    // without matching the
                                    // pattern `String s`
    default:
}

Both of these conditions apply only when the case pattern declares pattern variables. The following examples, in contrast, are unproblematic:

record R() {}
record S() {}
Object o = "Hello World";
switch (o) {
    case String s:
        System.out.println(s);      // No break
    case R():                       // No pattern variables declared
        System.out.println("It's either an R or a string");
        break;
    default:
}
Object ob = new R();
switch (ob) {
    case R():
    case S():                       // Multiple case labels
        System.out.println("Either R or an S");
        break;
    default:
}
Object obj = null;
switch (obj) {
    case null:
    case R():                       // Multiple case labels
        System.out.println("Either null or an R");
        break;
    default:
}

Sections: