☕ Java

break Statement

The break statement immediately terminates the nearest enclosing loop or switch block and transfers control to the first statement after that block. It is one of Java's three jump statements alongside continue and return. break is essential for exiting loops early when a search condition is met, preventing infinite loops from running forever, and stopping switch execution after a matched case.

How break Works

When the JVM encounters a break statement it immediately stops executing the current loop body or switch block and jumps to the first statement that follows the enclosing structure. The loop condition is not re-evaluated, no more iterations happen, and any code remaining in the current iteration is skipped. Execution resumes cleanly after the closing brace of the loop or switch. Without break, a switch case falls through to every subsequent case until the end of the block. Without break inside a loop, the loop can only terminate when its condition becomes false — which is a problem when the condition never becomes false (infinite loop) or when you need to exit early upon finding a specific value. break only exits the single innermost enclosing structure. If a break appears inside a for loop that is itself inside a while loop, only the for loop exits — the while loop continues normally. To exit multiple levels of nesting, Java provides labelled break.
Java
// ── break exits the nearest enclosing loop immediately: ──────────────
for (int i = 0; i < 10; i++) {
    if (i == 5) {
        break;          // exit the loop when i reaches 5
    }
    System.out.print(i + " ");
}
System.out.println("After loop");
// Output: 0 1 2 3 4 After loop
// The loop would normally run 10 times (i = 0..9).
// break stops it after 5 iterations.
// "After loop" still executes — break only exits the loop.

// ── Without break — loop runs to completion: ─────────────────────────
for (int i = 0; i < 10; i++) {
    System.out.print(i + " ");
}
// Output: 0 1 2 3 4 5 6 7 8 9

// ── break in a while loop: ────────────────────────────────────────────
int count = 0;
while (true) {              // infinite loop — only break can stop it
    if (count == 3) break;
    System.out.print(count + " ");
    count++;
}
System.out.println("Done");
// Output: 0 1 2 Done

// ── break in a do-while loop: ─────────────────────────────────────────
int n = 0;
do {
    if (n == 4) break;
    System.out.print(n + " ");
    n++;
} while (n < 10);
System.out.println("End");
// Output: 0 1 2 3 End

// ── break in switch — prevents fall-through: ─────────────────────────
int day = 3;
switch (day) {
    case 1:
        System.out.println("Monday");
        break;      // without break, execution falls to case 2
    case 2:
        System.out.println("Tuesday");
        break;
    case 3:
        System.out.println("Wednesday");
        break;      // executes, then break exits the switch
    default:
        System.out.println("Other day");
}
// Output: Wednesday

break in Search and Find Patterns

The most common real-world use of break is the search pattern — iterating over a collection or array looking for a specific element. Once the element is found there is no need to examine the remaining elements, so break exits the loop immediately. This optimisation is significant for large datasets: finding a value at index 2 in an array of one million elements means 999,998 unnecessary comparisons without break. The search pattern typically combines break with a boolean flag or a variable that records the result. After the loop, the flag or variable tells you whether the search succeeded. Alternatively, extracting the search into a method and using return instead of break produces cleaner code.
Java
// ── Search pattern — find first matching element: ────────────────────
int[] numbers = {14, 7, 23, 5, 42, 11, 8};
int target = 42;
int foundIndex = -1;        // -1 means "not found"

for (int i = 0; i < numbers.length; i++) {
    if (numbers[i] == target) {
        foundIndex = i;
        break;              // no need to check remaining elements
    }
}

if (foundIndex != -1) {
    System.out.println("Found " + target + " at index " + foundIndex);
} else {
    System.out.println(target + " not found");
}
// Output: Found 42 at index 4

// ── Without break — wastes time examining remaining elements: ─────────
// Even after finding 42 at index 4, the loop would continue
// checking indices 5 and 6 unnecessarily.

// ── Boolean flag pattern: ─────────────────────────────────────────────
String[] names = {"Alice", "Bob", "Charlie", "Diana"};
String search  = "Charlie";
boolean found  = false;

for (String name : names) {
    if (name.equals(search)) {
        found = true;
        break;
    }
}
System.out.println(search + (found ? " found" : " not found"));
// Output: Charlie found

// ── Cleaner: extract to a method, use return instead of break: ────────
public static int findIndex(int[] arr, int target) {
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] == target) {
            return i;       // return exits the method — cleaner than break
        }
    }
    return -1;
}

// ── Validation loop — keep prompting until valid input: ───────────────
Scanner scanner = new Scanner(System.in);
int age = 0;

while (true) {
    System.out.print("Enter age (1-120): ");
    if (scanner.hasNextInt()) {
        age = scanner.nextInt();
        if (age >= 1 && age <= 120) {
            break;          // valid input — exit the loop
        }
    } else {
        scanner.next();     // discard invalid token
    }
    System.out.println("Invalid age. Please try again.");
}
System.out.println("Age accepted: " + age);

Labelled break — Exiting Nested Loops

A plain break only exits the single innermost loop. When working with nested loops — such as searching a 2D matrix — you often want to exit all loops at once when a value is found. Java's labelled break achieves this by naming the outer loop with a label (an identifier followed by a colon placed immediately before the loop) and specifying that label after the break keyword. Labels are identifiers and follow the same naming rules as variables. Convention is to use uppercase names (OUTER, SEARCH, ROW_LOOP) to distinguish them from variable names. Labelled break is not a goto — it can only transfer control forward to the statement immediately after the labelled structure, never backwards or to an arbitrary location. Labelled breaks are not needed often, but when dealing with nested loops they are far cleaner than using boolean flags to propagate the exit condition through each level of nesting.
Java
// ── Plain break only exits the innermost loop: ───────────────────────
for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
        if (j == 1) break;          // exits inner loop only
        System.out.print("(" + i + "," + j + ") ");
    }
    // outer loop CONTINUES after inner loop exits
}
System.out.println();
// Output: (0,0) (1,0) (2,0)
// Inner loop breaks when j==1, but outer loop runs all 3 iterations.

// ── Labelled break exits both loops at once: ──────────────────────────
OUTER:                              // label on the outer loop
for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
        if (i == 1 && j == 1) {
            break OUTER;            // exits BOTH loops
        }
        System.out.print("(" + i + "," + j + ") ");
    }
}
System.out.println("After both loops");
// Output: (0,0) (0,1) (0,2) (1,0) After both loops
// When i=1, j=1: break OUTER exits the outer loop entirely.

// ── Practical: search in a 2D matrix: ────────────────────────────────
int[][] matrix = {
    {1,  2,  3,  4},
    {5,  6,  7,  8},
    {9, 10, 11, 12}
};
int searchVal = 7;
int foundRow = -1, foundCol = -1;

SEARCH:
for (int row = 0; row < matrix.length; row++) {
    for (int col = 0; col < matrix[row].length; col++) {
        if (matrix[row][col] == searchVal) {
            foundRow = row;
            foundCol = col;
            break SEARCH;           // exit both loops immediately
        }
    }
}

if (foundRow != -1) {
    System.out.printf("Found %d at [%d][%d]%n",
        searchVal, foundRow, foundCol);
} else {
    System.out.println(searchVal + " not found");
}
// Output: Found 7 at [1][2]

// ── Alternative using boolean flag (less clean): ──────────────────────
boolean done = false;
for (int row = 0; row < matrix.length && !done; row++) {
    for (int col = 0; col < matrix[row].length && !done; col++) {
        if (matrix[row][col] == searchVal) {
            foundRow = row;
            foundCol = col;
            done = true;    // signals outer loop to stop too
        }
    }
}
// Works, but the boolean flag is extra noise — labelled break is cleaner.

// ── Labels can be used with while and do-while too: ───────────────────
int x = 0, y = 0;
OUTER_WHILE:
while (x < 5) {
    while (y < 5) {
        if (x + y == 6) break OUTER_WHILE;
        y++;
    }
    y = 0;
    x++;
}
System.out.println("Stopped at x=" + x + " y=" + y);

break Inside switch Inside a Loop

A subtle and common mistake is placing a switch statement inside a loop and expecting break to exit the loop. Because break always exits the nearest enclosing structure, a break inside a switch exits the switch — not the loop. The loop continues as normal. To exit the loop from inside a switch, either use a labelled break targeting the loop, use a return statement if inside a method, or use a boolean flag.
Java
// ── COMMON MISTAKE: break inside switch inside loop exits switch only: ──
for (int i = 0; i < 5; i++) {
    switch (i) {
        case 3:
            System.out.println("Found 3, trying to exit loop...");
            break;          // exits the SWITCH — NOT the loop!
        default:
            System.out.println("i = " + i);
    }
}
// Output:
// i = 0
// i = 1
// i = 2
// Found 3, trying to exit loop...   ← break exited switch, loop continues
// i = 4
// The loop ran all 5 iterations despite the break at i=3.

// ── Fix 1: labelled break targeting the loop: ─────────────────────────
LOOP:
for (int i = 0; i < 5; i++) {
    switch (i) {
        case 3:
            System.out.println("Found 3, exiting loop.");
            break LOOP;     // exits the LOOP — correct
        default:
            System.out.println("i = " + i);
    }
}
// Output:
// i = 0
// i = 1
// i = 2
// Found 3, exiting loop.

// ── Fix 2: boolean flag: ──────────────────────────────────────────────
boolean exitLoop = false;
for (int i = 0; i < 5 && !exitLoop; i++) {
    switch (i) {
        case 3:
            System.out.println("Found 3.");
            exitLoop = true;
            break;          // exits switch; loop condition checked next
        default:
            System.out.println("i = " + i);
    }
}

// ── Fix 3: extract to a method and use return: ────────────────────────
public static void processSwitchInLoop() {
    for (int i = 0; i < 5; i++) {
        switch (i) {
            case 3:
                System.out.println("Found 3, returning.");
                return;     // exits the method — exits the loop too
            default:
                System.out.println("i = " + i);
        }
    }
}

Related Topics in Control Statements