Java Reference
In-Depth Information
This statement checks to see whether the status matches the value
0
,
1
,
2
, or
3
, in that
order. If matched, the corresponding tax is computed; if not matched, a message is displayed.
Here is the full syntax for the
switch
statement:
switch
(switch-expression) {
case
value1: statement(s)1;
break
;
case
value2: statement(s)2;
break
;
switch
statement
...
case
valueN: statement(s)N;
break
;
default
: statement(s)-for-default;
}
The
switch
statement observes the following rules:
The
switch-expression
must yield a value of
char
,
byte
,
short
,
int
, or
String
type and must always be enclosed in parentheses. (Using
String
type in
the
switch
expression is new in JDK 7.)
■
The
value1
, . . ., and
valueN
must have the same data type as the value of the
switch-expression
. Note that
value1
, . . ., and
valueN
are constant expres-
sions, meaning that they cannot contain variables, such as
1 + x
.
■
When the value in a
case
statement matches the value of the
switch-expression
,
the statements
starting from this case
are executed until either a
break
statement or
the end of the
switch
statement is reached.
■
The
default
case, which is optional, can be used to perform actions when none of
the specified cases matches the
switch-expression
.
■
The keyword
break
is optional. The
break
statement immediately ends the
switch
statement.
■
Caution
Do not forget to use a
break
statement when one is needed. Once a case is matched,
the statements starting from the matched case are executed until a
break
statement or
the end of the
switch
statement is reached. This is referred to as
fall-through
behavior.
For example, the following code displays the character
a
three times if
ch
is
a
:
without
break
fall-through behavior
switch
(ch) {
case
'a'
: System.out.println(ch);
case
'b'
: System.out.println(ch);
case
'c'
: System.out.println(ch);
}
true
System.out.println(ch)
ch is 'a'
false
true
System.out.println(ch)
ch is 'b'
false
true
System.out.println(ch)
ch is 'c'
false
Tip
To avoid programming errors and improve code maintainability, it is a good idea to put a
comment in a case clause if
break
is purposely omitted.