break / continue
break exits a loop, continue jumps to the next iteration; a label lets you leave a nested loop.
Available since: Java 1.0
Syntax
break; continue; break label;Examples
Skipping and exiting:
void main() {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue;
}
if (i > 7) {
break;
}
IO.println(i);
}
}Output:
1
3
5
7A label — leaving two loops at once:
void main() {
int[][] grid = {{1, 2, 3}, {4, 5, 6}};
outer:
for (int[] row : grid) {
for (int value : row) {
if (value == 5) {
IO.println("found 5");
break outer;
}
IO.println("checked " + value);
}
}
}Output:
checked 1
checked 2
checked 3
checked 4
found 5Notes
A plain break exits only the innermost loop or switch. A label is a name with a colon before a loop; continue outer jumps to the next iteration of the outer loop. If labels pile up, move the nested loop into a method and leave it with return.
See also
- for — A loop with a counter, or iteration over every element of an array or collection (for-each).
- while / do-while — Repeats a block while a condition is true; do-while runs it at least once.
- switch — Picks a branch by value; as an expression it returns a result.
In the tutorial
- Loop control — The break and continue statements in Java, leaving nested loops with labels and loops that exit from the middle.