Java Reference
In-Depth Information
The program produces the following output:
As you can see, the default
else
is executed only if none of the preceding
if
statements suc-
ceeds.
The switch Statement
The second of Java's selection statements is the
switch
. The
switch
provides for a multi-
way branch. Thus, it enables a program to select among several alternatives. Although a
series of nested
if
statements can perform multiway tests, for many situations the
switch
is a more efficient approach. It works like this: the value of an expression is successively
tested against a list of constants. When a match is found, the statement sequence associated
with that match is executed. The general form of the
switch
statement is