Break and Continue
Sometimes you need to fine-tune loop execution. You might want to stop the loop entirely based on a dynamic condition, or just skip the current iteration.
The break Statement
The break statement causes the loop to terminate
immediately. Control is transferred to the statement following the
loop.
Commonly used when searching for an item; once found, there is no need to keep searching.
for (int i = 0; i < 10; i++) {
if (i == 4) {
break; // Stop loop completely when i is 4
}
System.out.println(i);
}
The continue Statement
The continue statement skips the rest of the current
iteration and jumps back to the loop update/condition check. The
loop itself continues to run.
Commonly used to filter out invalid items.
for (int i = 0; i < 5; i++) {
if (i == 2) {
continue; // Skip 2, but go on to 3
}
System.out.println(i);
}
Click Run to execute your code
Labeled Loops (Nested Loops)
By default, break only exits the innermost loop. If you
want to break out of nested loops (e.g., stopping a matrix search), you can use
a label.
search: // This is a label
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (arr[i][j] == target) {
break search; // Exits BOTH loops
}
}
}
Summary
breakstops the loop entirely.continueskips the current iteration and goes to the next one.- Use labels to control nested loops from the inside.
Enjoying these tutorials?