It is sometimes necessary to exit from the middle of a loop.
Sometimes you'll want to start over at the top of the loop.
Sometimes you'll want to leave the loop completely. For these
purposes Java provides the break
and
continue
statements.
A continue
statement returns to the beginning of
the innermost enclosing loop without completing the rest of the
statements in the body of the loop. If you're in a for
loop, the counter is incremented. For example this code fragment
skips even elements of an array
for (int i = 0; i < m.length; i++) {
if (m[i] % 2 == 0) continue;
// process odd elements...
}
The continue
statement is rarely used in practice,
perhaps because most of the instances where it's useful have
simpler implementations. For instance, the above fragment could
equally well have been written as
for (int i = 0; i < m.length; i++) {
if (m[i] % 2 != 0) {
// process odd elements...
}
}
There are only seven uses of continue
in the entire
Java 1.0.1 source code for the java packages.