What is the continue keyword in Java?

Share

continue can be used to immediately jump to the next iteration of the loop (or exit the loop if the loop condition no longer holds). The remaining code in the current iteration is skipped.

widget

For loops

In for loops, a continue statement jumps directly to the update command and then on to the next iteration of the loop (or it exits the loop if the loop condition no longer holds).

widget

Example

In the following for loop, the print statement is skipped when the value of i is 33.

class ContinueLoop {
public static void main( String args[] ) {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
System.out.println(i);
}
}
}

In enhanced for loops, the behavior is similar: the loop variable is updated to point to the next element, and the next iteration runs.

for (Order order : orders) {
if (order.isProcessed()) {
// Continue to next order
continue;
}
process(order);
}

Nested loops

By default, continue only applies to the immediately enclosing loop. To make an outer loop continue, use labeled statements.

widget

continue is useful as it can make the loop more efficient. Certain operations will be skipped if they are not required.

Attributions:
  1. undefined by undefined