Explain continue statement with example?
It is sometimes essential to exit from the middle of a loop. Sometimes you'll need to begin over at the top of the loop. Sometimes you'll need to leave the loop completely. For these reasons Java gives the break
and continue
statements.
A continue
statement returns to the starting 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 instance this code fragment skips even parts 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 since most of the examples where it's meaningful have simpler implementations. For example, 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 just seven uses of continue
in the whole Java 1.0.1 source code for the java packages.