Labelled break and continue

Core Java · lesson 25 of 42 · 3 min read

Escape nested loops in one jump instead of juggling a found flag.

Open this lesson in the learning hub

Key points

  • A label is a name and a colon written in front of a loop: outer:.
  • break outer; leaves that whole loop, not just the innermost one.
  • continue outer; jumps straight to the next iteration of the labelled loop.
  • A plain break only ever exits the loop it sits in — the classic bug in a nested search.
  • The alternative is a boolean flag tested in both conditions, which is longer and easier to get wrong.
  • Use it for nested searches. Once you need three levels, extract a method and return instead.

Example

public class Main {
    public static void main(String[] args) {
        int[][] grid = {{1, 4}, {7, 9}, {2, 5}};
        int target = 7;

        int foundRow = -1;
        int foundCol = -1;

        outer:
        for (int r = 0; r < grid.length; r++) {
            for (int c = 0; c < grid[r].length; c++) {
                System.out.println("checking [" + r + "][" + c + "] = " + grid[r][c]);
                if (grid[r][c] == target) {
                    foundRow = r;
                    foundCol = c;
                    break outer;
                }
            }
        }
        System.out.println("found " + target + " at [" + foundRow + "][" + foundCol + "]");
        System.out.println("a plain break would only have left the inner loop");

        rows:
        for (int r = 0; r < grid.length; r++) {
            for (int c = 0; c < grid[r].length; c++) {
                if (grid[r][c] % 2 == 0) {
                    System.out.println("row " + r + " has an even value, jumping to the next row");
                    continue rows;
                }
                System.out.println("odd value " + grid[r][c] + " in row " + r);
            }
        }
    }
}

Label the outer loop when a single break has to escape both.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Core Java course, and every lesson in it is listed on the Core Java contents page.