Labeled Break Exits Nested Loops (Java)

A label on the outer loop lets break and continue jump out of both levels at once: search terminates on first hit, continue skips the whole row.

JavaData Fetching

Code

snippet
public class PairFinder {

    public static void main(String[] args) {
        int[][] grid = {
            {3, 7, 1},
            {8, 2, 4},
        };

        // labeled break:从嵌套循环内部一次性跳出两层
        search:
        for (int row = 0; row < grid.length; row++) {
            for (int col = 0; col < grid[row].length; col++) {
                if (grid[row][col] == 7) {
                    System.out.println("found 7 at [" + row + "][" + col + "]");
                    break search;
                }
            }
        }

        // labeled continue:结束本轮外层迭代,直接进入下一行
        evenScan:
        for (int row = 0; row < grid.length; row++) {
            for (int col = 0; col < grid[row].length; col++) {
                if (grid[row][col] % 2 == 1) {
                    continue evenScan; // 该行含奇数,整行跳过
                }
            }
            System.out.println("row " + row + " is all even");
        }
    }
}

How the file behaves

All of the logic lives in the class PairFinder and the function main.

One loop does the cycling here: for (int row = 0; row < grid.length; row++).

What to watch for

  • Dependency-free by design — no registry, no lockfile entry.

Using it

The main function’s signature: public static void main(String[] args)

Look for the found 7 at [, row prefixes once the file executes; the tags connect every line to the step behind it.

Key statements

continue evenScan; // 该行含奇数,整行跳过
}
break search;

Interactive Tools for This Topic

FAQ

What does Labeled Break Exits Nested Loops (Java) print when run?
Run it as a complete program — the output lines carry labels such as `found 7 at [`, `row`.