How do break and continue differ in Java, and what happens when they appear inside a nested loop?
Both act on the innermost enclosing loop, and that is the detail people get wrong. break abandons the loop entirely and execution continues with the statement after it. continue abandons only the current iteration and the loop starts its next one, skipping whatever was left in the body after the continue.
Inside nested loops, break only leaves the inner loop; the outer loop carries on with its next iteration. The same is true of continue. That is why a break in a double loop frequently leaves you still looping over the outer dimension when you thought you had exited completely.
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
System.out.println("continue at i=" + i);
continue; // skip the rest of this iteration
}
if (i == 5) {
System.out.println("break at i=" + i);
break; // leave the loop altogether
}
System.out.println("value " + i);
}
// In a nested loop, break only leaves the inner one.
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (j == 1) {
break;
}
System.out.println("i=" + i + " j=" + j);
}
}
}
}Two more points of precision. A break or continue inside a switch statement applies to the switch, not to any loop around it — so a break in a switch nested inside a for loop exits only the switch. And continue is not allowed inside a switch expression at all, since a switch expression must produce exactly one value and skipping part of the computation would make that ill-defined.