Memra

break, continue & labels

Jumping out of and skipping within loops.

Controlling the loop itself

break exits the nearest loop immediately. continue skips to the next iteration:

for (int i = 0; i < 10; i++) {
    if (i == 5) break;       // stop entirely at 5
    if (i % 2 == 0) continue; // skip evens
    System.out.println(i);    // prints 1, 3
}

For nested loops, a plain break only escapes the inner one. A labelled break escapes a chosen outer loop:

outer:
for (int r = 0; r < rows; r++) {
    for (int c = 0; c < cols; c++) {
        if (grid[r][c] == target) break outer;
    }
}

Labels are rare — usually a method with an early return reads better — but they're the clean way to bail out of nested loops.

NORMAL ~/memra/learn/java-from-zero/break-continue-labels utf-8 LF