Java Reference
In-Depth Information
Any statement immediately contained by the switch block may be labeled with one or more
switch labels
, which are
case
or
default
labels.
These labels are said to be
associated
with the
switch
statement, as are the values of the con-
All of the following must be true, or a compile-time error occurs:
• Every
case
constant expression associated with a
switch
statement must be as-
• No two of the
case
constant expressions associated with a
switch
statement may
have the same value.
• No switch label is
null
.
• At most one
default
label may be associated with the same
switch
statement.
The prohibition against using
null
as a switch label prevents one from writing
code that can never be executed. If the
switch
expression is of a reference type,
that is,
String
or a boxed primitive type or an enum type, then a run-time error
will occur if the expression evaluates to
null
at run time. In the judgment of
the designers of the Java programming language, this is a better outcome than
silently skipping the entire
switch
statement or choosing to execute the state-
ments (if any) after the
default
label (if any).
A Java compiler is encouraged (but not required) to provide a warning if a
switch
on an enum-valued expression lacks a
default
label and lacks
case
labels
for one or more of the enum type's constants. (Such a statement will silently
do nothing if the expression evaluates to one of the missing constants.)
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.