Java Loops: continue
continue
can be used to immediately continue to the next iteration of the loop (or exit the loop if the loop condition no longer holds).
In for
loops, a continue
statement jumps directly to the update statement and then on to the next iteration of the loop (or exits the loop if the loop condition no longer holds).
Example: At iteration 3, skip print statement
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
System.out.println(i);
}
Output:
1 2 4 5
In enhanced for
loops the behavior is similar: the loop variable is updated to point to the next element and the next iteration runs.
Example: Process all unprocessed orders
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 labelled statements.
Example: Continuing an inner vs an outer loop
Comments
Be the first to comment!