Java Reference
In-Depth Information
As you can see, each time through the loop, the statements associated with the
case
con-
stant that matches
i
are executed. All others are bypassed. When
i
is five or greater, no
case
statements match, so the
default
statement is executed.
Technically, the
break
statement is optional, although most applications of the
switch
will use it. When encountered within the statement sequence of a
case
, the
break
statement
causes program flow to exit from the entire
switch
statement and resume at the next state-
ment outside the
switch
. However, if a
break
statement does not end the statement se-
quence associated with a
case
, then all the statements
at and following
the matching
case
will be executed until a
break
(or the end of the
switch
) is encountered.
For example, study the following program carefully. Before looking at the output, can
you figure out what it will display on the screen?