Java Reference
In-Depth Information
When a switch statement is executed, one of a number of different branches is executed.
The choice of which branch to execute is determined by a controlling expression given in
parentheses after the keyword switch . Following this are a number of occurrences of
the reserved word case followed by a constant and a colon. These constants are called
case labels . The controlling expression for a switch statement must be one of the types
char , int , short , byte , or String . 1 The String data type is allowed only in Java 7
or higher. The case labels must all be of the same type as the controlling expression. No
case label can occur more than once, because that would be an ambiguous instruction.
There may also be a section labeled default :, which is usually last.
When the switch statement is executed, the controlling expression is evaluated and
the computer looks at the case labels. If it finds a case label that equals the value of the
controlling expression, it executes the code for that case label.
The switch statement ends when either a break statement is executed or the end
of the switch statement is reached. A break statement consists of the keyword break
followed by a semicolon. When the computer executes the statements after a case
label, it continues until it reaches a break statement. When the computer encounters
a break statement, the switch statement ends. If you omit the break statements, then
after executing the code for one case, the computer will go on to execute the code for
the next case.
Note that you can have two case labels for the same section of code, as in the
following portion of a switch statement:
controlling
expression
case labels
break
statement
case 'A':
case 'a':
System.out.println("Excellent. You need not take the final.");
break;
Because the first case has no break statement (in fact, no statements at all), the effect
is the same as having two labels for one case, but Java syntax requires one keyword case
for each label, such as 'A' and 'a' .
If no case label has a constant that matches the value of the controlling expression,
then the statements following the default label are executed. You need not have a
default section. If there is no default section and no match is found for the value
of the controlling expression, then nothing happens when the switch statement is
executed. However, it is safest to always have a default section. If you think your case
labels list all possible outcomes, you can put an error message in the default section.
The default case need not be the last case in a switch statement, but making it the
last case, as we have always done, makes the code clearer.
A sample switch statement is shown in Display 3.2. Notice that the case labels do
not need to be listed in order and do not need to span a complete interval.
default
1 As we will learn in Chapter 6 , the type may also be an enumerated type .
 
Search WWH ::




Custom Search