Phase 5 of 20 · Topic 5.4

Labelled Break & Continue Statements in Nested Loops

1Concept

In complex multi-dimensional search algorithms, a standard `break` only exits the innermost loop. Java provides labelled breaks (`break labelName;`) and labelled continues (`continue labelName;`) to break directly out of outer loop matrices.

2Architecture Diagram

OUTER_LOOP: for (...) {
  INNER_LOOP: for (...) {
    if (found) break OUTER_LOOP; ---> Jumps completely outside both loops!
  }
}

3Code Example

Core Java
public class LabelledLoopDemo {
    public static void main(String[] args) {
        int[][] matrix = {
            {10, 20, 30},
            {40, 99, 60},
            {70, 80, 90}
        };
        int target = 99;
        boolean found = false;

        SEARCH_MATRIX:
        for (int row = 0; row < matrix.length; row++) {
            for (int col = 0; col < matrix[row].length; col++) {
                if (matrix[row][col] == target) {
                    System.out.println("Found target " + target + " at row: " + row + ", col: " + col);
                    found = true;
                    break SEARCH_MATRIX; // Escapes both loops immediately!
                }
            }
        }
        System.out.println("Search terminated successfully: " + found);
    }
}

4Expected Output

Found target 99 at row: 1, col: 1
Search terminated successfully: true

5Key Takeaways

  • Labelled break is the only clean way to break out of nested iterations without boolean flags.
  • Labels must immediately precede the target loop statement.
  • Labelled continue skips to the next iteration of the outer labelled loop.