<code>break</code> and <code>continue</code> in Java β€” Plus Labelled Jumps

break exits a loop or switch immediately. continue skips the rest of the current iteration and jumps to the next. Both can target an outer loop via a label.

break

for (int i = 0; i < 100; i++) {
    if (i == target) {
        found = true;
        break;                  // exit the loop
    }
}

continue

for (String s : lines) {
    if (s.isEmpty()) continue;  // skip this iteration
    process(s);
}

Labelled break β€” exit nested loops

outer:
for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
        if (grid[i][j] == target) {
            found = true;
            break outer;         // exits BOTH loops
        }
    }
}

A label is an identifier followed by a colon, attached to a loop. break <label> jumps out of the labelled loop.

Labelled continue

outer:
for (Order o : orders) {
    for (Item i : o.items()) {
        if (i.isInvalid()) continue outer;   // next order, skip remaining items
    }
    process(o);
}

Alternatives to labels

Labels work but they're rare in modern Java. Often the cleanest alternative is extracting the inner logic into a method with an early return:

for (int i = 0; i < rows; i++) {
    if (findTargetInRow(grid[i])) { found = true; break; }
}

private boolean findTargetInRow(int[] row) {
    for (int v : row) if (v == target) return true;
    return false;
}

break in switch

switch (x) {
    case 1: doOne(); break;     // without break, falls through to case 2
    case 2: doTwo(); break;
    default: doOther();
}

The modern arrow-form switch expression (Java 14+) doesn't need break β€” there's no fall-through by default.

Common mistakes

  • Using a label for simple cases β€” a flag variable or extracted method is usually cleaner.
  • Forgetting break in a classic switch β€” fall-through bugs. Use arrow syntax.
  • continue in while that skips the update β€” make sure the loop condition still progresses.

Related

Pillar: Java control flow. See also for loop, switch.