Java Reference
In-Depth Information
the
'A'
case in the previous example was not there, both the
aCount
and
bCount
variables would be incremented when the
idChar
con-
tains an
'A'
. Usually we want to perform only one case, so a
break
statement is almost always used. Occasionally, though, the “pass
through” feature comes in handy.
You'll remember that the
break
statement was briefly mentioned
in Chapter 5, because it could be used in other types of loops and conditionals.
We warned then that such processing is usually unnecessary and its use is consid-
ered by many developers to be bad practice. The
switch
statement is the excep-
tion to this guideline. Using a
break
statement is the only way to make sure the
code for only one case is executed.
KEY CONCEPT
A
break
statement is usually used at
the end of each case alternative of a
switch
statement.
Switch Statement
switch
(
Expression
)
{
}
Switch Case
Switch Case
case
Expression
:
Block Statement
default
:
The
switch
statement evaluates the initial Expression and matches
its value with one of the cases. Processing continues with the Statement
corresponding to that case. The optional
default
case will be executed if
no other case matches.
Example:
switch
(numValues)
{
case
0:
System.out.println ("No values were entered.");
break;
case
1:
System.out.println ("One value was entered.");
break;
case
2:
System.out.println ("Two values were entered.");
break;
default:
System.out.println ("Too many values were entered.");
}
The expression evaluated at the beginning of a
switch
statement must be of
type
char
,
byte
,
short
, or
int
. In particular, it cannot be a
boolean
, or a floating
point value, or a
String
. Furthermore, the value of each case must be a constant;
it cannot be a variable or other expression. This limits the situations in which a
switch
statement is appropriate. But when it is appropriate, it usually makes the
code easier to read and understand.
Search WWH ::
Custom Search