Java Reference
In-Depth Information
The following is a revision of the nested
if
example shown previously. It has been
rewritten as a
switch
statement:
switch (operation) {
case '+':
add(object1, object2);
break;
case '-':
subtract(object1, object2);
break;
case '*':
multiply(object1, object2);
break;
case '/':
divide(object1, object2);
break;
}
After each
case
, you can include a single result statement or as many as you need.
Unlike with
if
statements, multiple statements don't require a block statement.
The
break
statement included with each
case
section determines when to stop executing
statements in response to a matching
case
. Without a
break
statement in a
case
section,
after a match is made, the statements for that match and all the statements further down
the
switch
are executed until a
break
or the end of the switch is found.
In some situations, this might be exactly what you want to do. Otherwise, you should
include
break
statements to ensure that only the right code is executed. The
break
state-
ment, which you use again later in the section “Breaking Out of Loops,” stops execution
at the current point and jumps to the statement after the closing brace that ends the
switch
statement.
One handy use of falling through without a
break
occurs when multiple values need to
execute the same statements. To accomplish this task, you can use multiple
case
lines
with no result; the
switch
executes the first statement that it finds.
For example, in the following
switch
statement, the string
x is an even number
is
printed if
x
has the values of 2, 4, 6, or 8. All other values of
x
cause the string
x is an
odd number
to be printed.
switch (x) {
case 2:
case 4:
case 6:
case 8:
System.out.println(“x is an even number”);
break;
default: System.out.println(“x is an odd number”);
}