The switch statement transfers control to one of several statements or expressions, depending on the value of an expression.
SwitchStatement:
switch ( Expression ) SwitchBlock
The Expression is called the selector expression. The type of the selector expression must be char, byte, short, int, Character, Byte, Short, Integer, String, or an enum type (§8.9), or a compile-time error occurs.
14.11.1. Switch Blocks
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}
default
CaseConstant:
ConditionalExpression
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 has one or more case constants. Every case constant must be either a constant expression (§15.29) or the name of an enum constant (§8.9.1), or a compile-time error occurs.
Switch labels and their case constants are said to be associated with the switch block. No two of the case constants associated with a switch block may have the same value, or a compile-time error occurs.
The switch block of a switch statement or a switch expression is compatible with the type of the selector expression, T, if both of the following are true:
- If T is not an enum type, then every
caseconstant associated with the switch block is assignment compatible with T (§5.2). - If T is an enum type, then every
caseconstant associated with the switch block is an enum constant of type T.
The switch block of a switch statement or a switch expression must be compatible with the type of the selector expression, or a compile-time error occurs.
Both the execution of a switch statement (§14.11.3) and the evaluation of a switch expression (§15.28.2) need to determine if a switch label matches the value of the selector expression. To determine whether a switch label in a switch block matches a given value, the value is compared with the case constants associated with the switch block. Then:
-
If one of the
caseconstants is equal to the value, then we say that thecaselabel which contains thecaseconstant matches.Equality is defined in terms of the
==operator (§15.21) unless the value is aString, in which case equality is defined in terms of theequalsmethod of classString. -
If no
caselabel matches but there is adefaultlabel, then we say that thedefaultlabel matches.
A case label can contain several case constants. The label matches the value of the selector expression if any one of its constants matches the value of the selector expression. For example, in the following code, the case label matches if the enum variable day is either one of the enum constants shown:
switch (day) {
...
case SATURDAY, SUNDAY :
System.out.println("It's the weekend!");
break;
...
}
null cannot be used as a case constant because it is not a constant expression. Even if case null was allowed, it would be undesirable because the code in that case can never be executed. Namely, if the selector expression is of a reference type (that is, String or a boxed primitive type or an enum type), then an exception will occur if the selector expression evaluates to null at run time. In the judgment of the designers of the Java programming language, propagating the exception is a better outcome than either having no case label match, or having the default label match.
In C and C++ the body of a switch statement can be a statement and statements with case labels do not have to be immediately contained by that statement. Consider the simple loop:
for (i = 0; i < n; ++i) foo();
where n is known to be positive. A trick known as Duff's device can be used in C or C++ to unroll the loop, but this is not valid code in the Java programming language:
int q = (n+7)/8;
switch (n%8) {
case 0: do { foo(); // Great C hack, Tom,
case 7: foo(); // but it's not valid here.
case 6: foo();
case 5: foo();
case 4: foo();
case 3: foo();
case 2: foo();
case 1: foo();
} while (--q > 0);
}
Fortunately, this trick does not seem to be widely known or used. Moreover, it is less needed nowadays; this sort of code transformation is properly in the province of state-of-the-art optimizing compilers.
14.11.2. The Switch Block of a switch Statement
In addition to the general rules for switch blocks (§14.11.1), there are further rules for switch blocks in switch statements. Namely, all of the following must be true for the switch block of a switch statement, or a compile-time error occurs:
- No more than one
defaultlabel is associated with theswitchblock. - 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).
14.11.3. Execution of a switch Statement
A switch statement is executed by first evaluating the selector expression. Then:
- If evaluation of the selector expression completes abruptly, then the entire
switchstatement completes abruptly for the same reason. - Otherwise, if the result of evaluating the selector expression is
null, then aNullPointerExceptionis thrown and the entireswitchstatement completes abruptly for that reason. - Otherwise, if the result of evaluating the selector expression is of type
Character,Byte,Short, orInteger, it is subjected to unboxing conversion (§5.1.8). If this conversion completes abruptly, the entireswitchstatement completes abruptly for the same reason.
If evaluation of the selector expression completes normally and the result is non-null, and the subsequent unboxing conversion (if any) completes normally, then execution of the switch statement continues by determining if a switch label associated with the switch block matches the value of the selector expression (§14.11.1). Then:
-
If no switch label matches, the entire
switchstatement completes normally. -
If a switch label matches, then one of the following applies:
- If it is the switch label for a switch rule expression, then the switch rule expression is necessarily a statement expression (§14.11.2). The statement expression is evaluated. If the evaluation completes normally, then the
switchstatement completes normally. If the result of evaluation is a value, it is discarded. - If it is the switch label for a switch rule block, then the block is executed. If this block completes normally, then the
switchstatement completes normally. - If it is the switch label for a switch rule
throwstatement, then thethrowstatement is executed. - If it is the switch label for a switch labeled statement group, then all the statements in the switch block that follow the switch label are executed in order. If these statements complete normally, then the
switchstatement completes normally. - Otherwise, there are no statements that follow the matched switch label in the switch block, and the
switchstatement completes normally.
- If it is the switch label for a switch rule expression, then the switch rule expression is necessarily a statement expression (§14.11.2). The statement expression is evaluated. If the evaluation completes normally, then the
If execution of any statement or expression in the switch block completes abruptly, it is handled as follows:
-
If execution of a statement completes abruptly because of a
breakwith no label, then no further action is taken and theswitchstatement completes normally.Abrupt completion because of a
breakwith a label is handled by the general rule for labeled statements (§14.7). -
If execution of a statement or expression completes abruptly for any other reason, then the
switchstatement completes abruptly for the same reason.Abrupt completion because of a
yieldstatement is handled by the general rule for switch expressions (§15.28.2).
Example 14.11.3-1. Fall-Through in the switch Statement
When a selector expression matches a switch label for a switch rule, the switch rule expression or statement introduced by the switch label is executed, and nothing else. In the case of a switch label for a statement group, all the block statements in the switch block that follow the switch label are executed, including those that appear after subsequent switch labels. The effect is that, as in C and C++, execution of statements can "fall through labels."
For example, the program:
class TooMany {
static void howMany(int k) {
switch (k) {
case 1: System.out.print("one ");
case 2: System.out.print("too ");
case 3: System.out.println("many");
}
}
public static void main(String[] args) {
howMany(3);
howMany(2);
howMany(1);
}
}
contains a switch block in which the code for each case falls through into the code for the next case. As a result, the program prints:
many
too many
one too many
Fall through can be the cause of subtle bugs. If code is not to fall through case to case in this manner, then break statements can be used to indicate when control should be transferred, or switch rules can be used, as in the program:
class TwoMany {
static void howMany(int k) {
switch (k) {
case 1: System.out.println("one");
break; // exit the switch
case 2: System.out.println("two");
break; // exit the switch
case 3: System.out.println("many");
break; // not needed, but good style
}
}
static void howManyAgain(int k) {
switch (k) {
case 1 -> System.out.println("one");
case 2 -> System.out.println("two");
case 3 -> System.out.println("many");
}
}
public static void main(String[] args) {
howMany(1);
howMany(2);
howMany(3);
howManyAgain(1);
howManyAgain(2);
howManyAgain(3);
}
}
This program prints:
one
two
many
one
two
many