continue statements

index
INTERMEDIATE

The syntax of a continue statement is very simple:

continue;

Within any kind of a loop, continue causes execution to go directly to the test of the while loop or do-while loop, or to the increment part of the for loop.

There is very little point in having a "bare" continue that unconditionally exits a loop. Almost always, the continue is embedded in an if statement. For example:

int totalOfPositiveNumbers = 0;
for (int i = 0; i < myArray.length; i++) {
    if (myArray[i] < 0) {
        continue;
    }
    totalOfPositiveNumbers++;
}

Unlike break, continue may only be used in loops, not in switch statements.

STYLE

Loops containing a continue statement can often be simplified. For example, the above code could be rewritten as:

int totalOfPositiveNumbers = 0;
for (int i = 0; i < myArray.length; i++) {
    if (myArray[i] > 0) {
        totalOfPositiveNumbers++;
    }
}