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 [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 rulethrowstatement; 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 consists of either a list of case constants, a null literal, or a case pattern.
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 a case pattern may have an optional when expression, known as a guard, which represents a further test on values that match the pattern. 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.
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
caseconstants associated with a switch block may have the same value. - No more than one
nullliteral may be associated with a switch block. - No more than one
defaultlabel 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
booleanorBoolean. - Any local variable, formal parameter, or exception parameter used but not declared in a guard must either be
finalor effectively final (§4.12.4). - Any blank
finalvariable 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
nullliteral is associated with the switch block, then T is a reference type. - For every
caseconstant associated with the switch block that names an enum constant, the type of thecaseconstant is assignment compatible with T (§5.2). - For each
caseconstant associated with the switch block that is a constant expression, the constant is assignment compatible with T, and T is one ofchar,byte,short,int,Character,Byte,Short,Integer, orString. - Every pattern
passociated 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
caselabel with acasepatternqis dominated if there is a preceding unguardedcaselabel in the switch block with acasepatternp, andpdominatesq(§14.30.3).The definition of one pattern dominating another pattern is based on types. For example, the type pattern
Objectodominates the type patternStrings, 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
caselabel with acasepattern is dominated by acaselabel 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
caselabel with acasepattern is not considered to dominate an unguardedcaselabel with the samecasepattern. 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
caselabel with acaseconstantcis dominated if one of the following holds:cis a constant expression of a primitive type S, and there is a precedingcaselabel in the switch block with an unguardedcasepatternp, wherepis unconditional for the wrapper class of S.cis a constant expression of a reference type T, and there is a precedingcaselabel in the switch block with an unguardedcasepatternp, wherepis unconditional for the type T.cnames an enum constant of enum class E, and there is a precedingcaselabel in the switch block with an unguardedcasepatternp, wherepis unconditional for the type E.
For example, a
caselabel with anIntegertype pattern dominates acaselabel 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
defaultlabel or acasenull,defaultlabel is dominated if there is a preceding unguardedcaselabel in the switch block with acasepatternpwherepis unconditional for the type of the selector expression (§14.30.3).A
caselabel with acasepattern that is unconditional for the type of the selector expression will, as the name suggests, match every value and so behave like adefaultlabel. A switch block can not have more than one switch label that acts like adefault.
It is a compile-time error if any of the following holds:
- There is a
defaultlabel in the switch block that precedes acaselabel with acasepattern. - There is a
defaultlabel in the switch block that precedes acaselabel with anullliteral. - There is a
casenull,defaultlabel 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 a case pattern.
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 pattern that declares one or more pattern variables, 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: