Java Reference
In-Depth Information
The
continue
keyword starts the loop over at the next iteration. For
do
and
while
loops,
this means that the execution of the block statement starts over again; with
for
loops, the
increment expression is evaluated, and then the block statement is executed.
The
continue
keyword is useful when you want to make a special case out of elements
within a loop. With the previous example of copying one array to another, you could test
for whether the current element is equal to 1 and use
continue
to restart the loop after
every 1 so that the resulting array never contains zero. Note that because you're skipping
elements in the first array, you now have to keep track of two different array counters:
int count = 0;
int count2 = 0;
while (count++ <= array1.length) {
if (array1[count] == 1)
continue;
array2[count2++] = (float)array1[count];
}>
Labeled Loops
Both
break
and
continue
can have an optional label that tells Java where to resume exe-
cution of the program. Without a label,
break
jumps outside the nearest loop to an
enclosing loop or to the next statement outside the loop. The
continue
keyword restarts
the loop it is enclosed within. Using
break
and
continue
with a label enables you to use
break
to go to a point outside a nested loop or to use
continue
to go to a loop outside
the current loop.
To use a labeled loop, add the label before the initial part of the loop, with a colon
between the label and the loop. Then, when you use
break
or
continue
, add the name of
the label after the keyword itself, as in the following:
out:
for (int i = 0; i <10; i++) {
while (x < 50) {
if (i * x++ > 400)
break out;
// inner loop here
}
// outer loop here
}
In this snippet of code, the label
out
labels the outer loop. Then, inside both the
for
and
while
loops, when a particular condition is met, a
break
causes the execution to break
out of both loops. Without the label
out
, the
break
statement would exit the inner loop
and resume execution with the outer loop.