SwadhyAI Notes

All Java notes

Java break and continue

›Short versionOpen if you only have a minute.
  • break leaves the innermost loop. Statements after the loop run. The for-loop update does not.
  • continue skips the rest of this pass. In a for loop the update still runs, then the condition is tested.
  • In a while, continue jumps to the test. An increment written below the continue is skipped.
  • In nested loops, an unlabeled break or continue affects only the inner loop.
  • A label on the outer loop is how break or continue names that outer loop.

and change which lines of a loop run. They do not change the loop's bound by themselves. Used in the wrong place, continue is also how a while loop stops making progress.

java
for (int i = 0; i < 10; i++) {
    if (i == 4) {
        break;
    }
    System.out.println(i);
}

What the console shows

0
1
2
3

When i is 4 the loop ends. The print under the if does not run for 4, and the later values are never visited. The i++ does not run for that interrupted pass, because the loop is over.

Skip one pass, keep the step

continue is the smaller interruption. The loop remains. One value is left out.

java
for (int i = 0; i < 6; i++) {
    if (i == 4) {
        continue;
    }
    System.out.println(i);
}

The prints are 0, 1, 2, 3, and 5. At 4 the rest of the body is skipped, then i++ still runs, then the condition allows 5. That header update is why this loop ends. The same continue sitting above i++ inside a while would keep i at 4 forever.

Only the loop that contains the statement

A does not give break a longer reach. The statement leaves the innermost loop. The outer one proceeds to its next pass and starts the inner loop again.

java
for (int i = 1; i <= 2; i++) {
    for (int j = 1; j <= 3; j++) {
        if (j == 2) {
            break;
        }
        System.out.println(i + ", " + j);
    }
}

What the console shows

1, 1
2, 1

Each outer pass prints one line and then the inner break drops the rest of that row. The outer loop still runs for i equal to 2. A is what you write when finding j == 2 should abandon both loops: put search: on the outer for, and write break search;.

Inside a switch, break means “leave the switch,” which is the stop that prevents fall-through. That break does not leave a loop wrapped around the switch. The two uses share a word and not a target.

The nested loops above break when j is 2. Why does a line for i equal to 2 still print?

The break is inside the inner loop, so it leaves only that loop. After the inner loop ends, the outer loop runs its update, i becomes 2, and a new inner loop starts. break search; with a label on the outer loop is what would have stopped both.