Java Reference
In-Depth Information
break
;
// Stop here
}
As you can see from the example, the various entry points into a
switch
statement
are labeled either with the keyword
case
, followed by an integer value and a colon,
or with the special
default
keyword, followed by a colon. When a
switch
statement
executes, the interpreter computes the value of the expression in parentheses and
then looks for a
case
label that matches that value. If it finds one, the interpreter
starts executing the block of code at the first statement following the
case
label. If it
does not find a
case
label with a matching value, the interpreter starts execution at
the first statement following a special-case
default
: label. Or, if there is no
default
:
label, the interpreter skips the body of the
switch
statement altogether.
Note the use of the
break
keyword at the end of each
case
in the previous code. The
break
statement is described later in this chapter, but, in this case, it causes the
interpreter to exit the body of the
switch
statement. The
case
clauses in a
switch
statement specify only the starting point of the desired code. The individual cases
are not independent blocks of code, and they do not have any implicit ending point.
Therefore, you must explicitly specify the end of each case with a
break
or related
statement. In the absence of
break
statements, a
switch
statement begins executing
code at the first statement after the matching
case
label and continues executing
statements until it reaches the end of the block. On rare occasions, it is useful to
write code like this that falls through from one
case
label to the next, but 99% of the
time you should be careful to end every
case
and
default
section with a statement
that causes the
switch
statement to stop executing. Normally you use a
break
state‐
ment, but
return
and
throw
also work.
a
x
A
switch
statement can have more than one
case
clause labeling the same state‐
ment. Consider the
switch
statement in the following method:
boolean
parseYesOrNoResponse
(
char
response
)
{
switch
(
response
)
{
case
'y'
:
case
'Y'
:
return
true
;
case
'n'
:
case
'N'
:
return
false
;
default
:
throw
new
IllegalArgumentException
(
"Response must be Y or N"
);
}
}
The
switch
statement and its
case
labels have some important restrictions. First,
the expression associated with a
switch
statement must have an appropriate type—
either
byte
,
char
,
short
,
int
(or their wrappers), or an enum type or a
String
. The
floating-point and
boolean
types are not supported, and neither is
long
, even
though
long
is an integer type. Second, the value associated with each
case
label
must be a constant value or a constant expression the compiler can evaluate. A
case
label cannot contain a runtime expression involving variables or method calls, for
example. Third, the
case
label values must be within the range of the data type used