Java Reference
In-Depth Information
}
else
{
if
(
n
==
2
)
{
// Execute code block #2
}
else
{
if
(
n
==
3
)
{
// Execute code block #3
}
else
{
// If all else fails, execute block #4
}
}
}
The switch Statement
An
if
statement causes a branch in the flow of a program's execution. You can use
multiple
if
statements, as shown in the previous section, to perform a multiway
branch. This is not always the best solution, however, especially when all of the
branches depend on the value of a single variable. In this case, it is inefficient to
repeatedly check the value of the same variable in multiple
if
statements.
A better solution is to use a
switch
statement, which is inherited from the C pro‐
gramming language. Although the syntax of this statement is not nearly as elegant
as other parts of Java, the brute practicality of the construct makes it worthwhile.
A
switch
statement starts with an expression whose type is an
int
,
short
,
char
,
byte
(or their wrapper type),
String
, or an
enum (see
Chapter 4
for more on enumerated types).
This expression is followed by a block of code in curly braces that contains various
entry points that correspond to possible values for the expression. For example, the
following
switch
statement is equivalent to the repeated
if
and
else/if
statements
shown in the previous section:
switch
(
n
)
{
case
1
:
// Start here if n == 1
// Execute code block #1
break
;
// Stop here
case
2
:
// Start here if n == 2
// Execute code block #2
break
;
// Stop here
case
3
:
// Start here if n == 3
// Execute code block #3
break
;
// Stop here
default
:
// If all else fails...
// Execute code block #4