Java Reference
In-Depth Information
The
break
and
continue
Statements
★
In previous subsections, we described the basic flow of control for the
while
,
do-while
,
and
for
loops. This is how the loops should normally be used and is the way they are
usually used. However, you can alter the flow of control in two additional ways. The two
ways of altering the flow of control are to insert either a
break
or a
continue
statement.
The
break
statement ends the loop. The
continue
statement ends the current iteration
of the loop body. The
break
and
continue
statements can be used with any of the Java
loop statements.
We described the
break
statement earlier when we discussed the
switch
statement.
The
break
statement
consists of the keyword
break
followed by a semicolon. When
executed, the
break
statement ends the nearest enclosing
switch
or loop statement.
The
continue
statement
consists of the keyword
continue
followed by a semico-
lon. When executed, the
continue
statement ends the current loop body iteration of
the nearest enclosing loop statement.
One point that you should note when using the
continue
statement in a
for
loop
is that the
continue
statement transfers control to the update expression. Thus, any
loop control variable will be updated immediately after the
continue
statement is exe-
cuted.
Note that a
break
statement completely ends the loop. In contrast, a
continue
state-
ment merely ends one loop iteration, and the next iteration (if any) continues the loop.
You never absolutely need a
break
or
continue
statement. Any code that uses a
break
or
continue
statement can be rewritten to do the same thing without a
break
or
continue
statement. The
continue
statement can be particularly tricky and can make your code
hard to read. It may be best to avoid the
continue
statement completely or at least use it
only on very rare occasions. The use of the
break
and
continue
statements in loops is
controversial, with many experts saying they should never be used. You will need to
make your own decision on whether you will use either or both of these statements.
You can nest one loop statement inside another loop statement. When doing so,
remember that any
break
or
continue
statement applies to the innermost loop state-
ment containing the
break
or
continue
statement. If there is a
switch
statement
inside a loop, any
break
statement applies to the innermost loop or
switch
statement.
There is a type of
break
statement that, when used in nested loops, can end any
containing loop, not just the innermost loop. If you label an enclosing loop statement
with an
Identifier
, then the following version of the
break
statement will exit the
labeled loop, even if it is not the innermost enclosing loop:
break
statement
continue
statement
break
Identifier;
label
To
label
a loop statement, simply precede it with an
Identifier
and a colon. The fol-
lowing is an outline of some sample code that uses a labeled
break
statement:
outerLoop:
do