Normally inside nested loops break
and
continue
exit the innermost enclosing loop. For example
consider the following loops.
for (int i=1; i < 10; i++) {
for (int j=1; j < 4; j++) {
if (j == 2) break;
System.out.println(i + ", " + j);
}
}
This code fragment prints
1, 1
2, 1
3, 1
4, 1
5, 1
6, 1
7, 1
8, 1
9, 1
because you break out of the innermost loop when j is two. However the outermost loop continues.
To break out of both loops, label the outermost loop and indicate that label in the break statement like this:
iloop: for (int i=1; i < 3; i++) {
for (int j=1; j < 4; j++) {
if (j == 2) break iloop;
System.out.println(i + ", " + j);
}
}
This code fragment prints
1, 1
and then stops because j
is two and the outermost loop
is exited.