5.4 Branching with Break and Continue

Key Takeaways

  • In nested loops, the inner loop executes its complete lifecycle from start to finish for every individual iteration of the outer loop, multiplying the overall iteration count.
  • An unlabeled break statement terminates only the innermost enclosing loop or switch statement, immediately resuming execution at the statement following that block.
  • An unlabeled continue statement skips the remainder of the innermost loop's body, jumping directly to the update expression in a for loop or to the condition test in a while/do-while loop.
  • Labeled break and continue statements (break label; / continue label;) allow multi-level branching, enabling code to escape or cycle outer enclosing loops from deep within nested loops.
  • Code placed immediately following an unconditional break or continue statement within the same execution block triggers a fatal compile-time 'unreachable statement' error.
Last updated: September 2026

5.4 Branching with Break and Continue

[!NOTE] Exam Focus: Branching statements combined with nested loops represent some of the most intricate code-reading challenges on the 1Z0-811 examination. Candidates must master the distinct behaviors of break versus continue, understand how their jump destinations differ across for and while loops, trace labeled multi-level jumps, and identify compile-time unreachable statement errors.

While sequential loop iterations proceed from start to finish based on the loop header condition, real-world algorithms frequently require early termination or conditional skipping. In Java, control flow can be altered dynamically using the branching keywords break and continue, which can operate either as unlabeled statements or in conjunction with statement labels.


Nested Loops: Hierarchy and Iteration Mechanics

A nested loop is a loop placed inside the body of another loop. When loops are nested, the inner loop executes its entire lifecycle from beginning to end for every single iteration of the outer loop.

for (int outer = 1; outer <= 3; outer++) {
    for (int inner = 1; inner <= 2; inner++) {
        System.out.println("outer=" + outer + ", inner=" + inner);
    }
}

The Iteration Multiplication Rule

When the boundary conditions of both loops are independent, the total number of inner loop executions follows the fundamental multiplication principle:

Total Inner Executions=Outer Loop Count×Inner Loop Count\text{Total Inner Executions} = \text{Outer Loop Count} \times \text{Inner Loop Count}

In the snippet above, the outer loop executes 3 times and the inner loop executes 2 times per outer iteration, resulting in $3 \times 2 = 6$ total print statements:

  1. outer=1, inner=1
  2. outer=1, inner=2
  3. outer=2, inner=1
  4. outer=2, inner=2
  5. outer=3, inner=1
  6. outer=3, inner=2

Variable-Bound Inner Loops (Triangular Patterns)

In many algorithms, the inner loop's termination condition depends directly on the outer loop's current counter:

for (int i = 1; i <= 4; i++) {
    for (int j = 1; j <= i; j++) {
        System.out.print("*");
    }
    System.out.println();
}

Here, when i=1, j runs 1 time; when i=2, j runs 2 times; when i=3, j runs 3 times; and when i=4, j runs 4 times. Total inner executions = $1 + 2 + 3 + 4 = 10$.


The break Statement

The break statement immediately terminates the execution of the innermost enclosing loop (for, while, or do-while) or switch statement in which it appears. Control transfers immediately to the first statement following the loop's closing curly brace.

for (int i = 1; i <= 5; i++) {
    if (i == 3) {
        break; // Terminates loop immediately when i is 3
    }
    System.out.print(i + " ");
}
System.out.println("Done");
// Output: 1 2 Done

Syntactic Rules and Constraints for break

  1. Innermost Target: By default, an unlabeled break terminates only the innermost loop enclosing it. Any outer loops continue running normally.
  2. Permitted Contexts: A break statement can appear only inside a loop construct (for, while, do-while) or a switch statement. Placing a break inside a standalone if block that is not enclosed within a loop or switch causes an immediate compile-time error (break outside switch or loop).
  3. Unreachable Code Traps: Placing a statement immediately following an unconditional break within the same block triggers a fatal compile-time "unreachable statement" error:
    while (true) {
        break;
        System.out.println("Error!"); // COMPILE ERROR: unreachable statement
    }
    

The continue Statement

The continue statement skips the remainder of the current iteration's body and transfers control directly to the start of the next iteration of the innermost enclosing loop.

Crucial Destination Differences Between Loop Types

A major conceptual topic on the 1Z0-811 exam is recognizing where continue jumps based on the enclosing loop type:

In a for loop:         continue ───────────> Jumps to UPDATE EXPRESSION (i++)
In a while loop:       continue ───────────> Jumps to CONDITION TEST (count < 5)
In a do-while loop:    continue ───────────> Jumps to CONDITION TEST (while(cond);)
for (int i = 1; i <= 5; i++) {
    if (i % 2 == 0) {
        continue; // Skips even numbers; jumps straight to i++ in header
    }
    System.out.print(i + " ");
}
// Output: 1 3 5 

The while Loop Infinite Increment Trap

A favorite trap crafted by exam authors involves invoking continue inside a while loop prior to incrementing the loop control variable:

int count = 1;
while (count <= 5) {
    if (count == 3) {
        continue; // TRAP! Bypasses count++ below! count remains 3 forever!
    }
    System.out.print(count + " ");
    count++; // Skipped whenever count is 3
}

When count reaches 3, continue transfers control directly to the condition count <= 5. Because count++ was skipped, count remains 3 indefinitely, creating an unbreakable infinite loop!

Permitted Contexts for continue

Unlike break (which can appear in loops or switch statements), continue can only appear inside loop constructs. Using continue inside a switch statement that is not enclosed within a loop triggers a compile-time error (continue outside of loop).


Labeled Statements and Multi-Level Branching

When loops are nested, an unlabeled break or continue can only influence the innermost loop. To break out of or continue an outer enclosing loop from within a nested inner loop, Java provides labeled statements.

Label Syntax

A label is any legal Java identifier followed immediately by a colon (:), placed directly preceding a loop statement:

OUTER_LOOP: for (int i = 1; i <= 3; i++) {
    INNER_LOOP: for (int j = 1; j <= 3; j++) {
        // Statements
    }
}

1. Labeled break

A labeled break immediately terminates the specific loop associated with that label, even if invoked from several nesting levels deep:

ROW_LOOP: for (int row = 0; row < 3; row++) {
    for (int col = 0; col < 3; col++) {
        if (row == 1 && col == 1) {
            break ROW_LOOP; // Terminates the ENTIRE outer ROW_LOOP immediately!
        }
        System.out.println("row=" + row + ", col=" + col);
    }
}
System.out.println("Exited");

Console Output:

row=0, col=0
row=0, col=1
row=0, col=2
row=1, col=0
Exited

As soon as row == 1 && col == 1 occurs, break ROW_LOOP; halts the outer loop entirely. Neither the remainder of row 1 nor any of row 2 executes.

2. Labeled continue

A labeled continue skips the remainder of the current inner loop body AND transfers control directly to the update expression (for a for loop) or condition test (for a while loop) of the specified labeled outer loop:

OUTER: for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 3; j++) {
        if (j == 2) {
            continue OUTER; // Abandons inner loop; jumps straight to i++ in OUTER
        }
        System.out.println("i=" + i + ", j=" + j);
    }
}

Console Output:

i=1, j=1
i=2, j=1
i=3, j=1

In each outer pass, as soon as j reaches 2, continue OUTER; skips the remainder of the inner loop and immediately jumps to i++ of OUTER. Consequently, the inner loop never executes for j=3.


Unreachable Code Traps in Branching Statements (JLS §14.21)

The Java compiler rigorously analyzes control flow reachability after branching statements:

for (int i = 0; i < 5; i++) {
    if (i == 2) {
        continue;
        System.out.println("Unreachable!"); // COMPILE ERROR: unreachable statement
    }
}

Any statement written inside the same block immediately following an unconditional break, continue, or return is statically unreachable and causes a compilation failure.

However, if the branching statement is wrapped inside a conditional block, subsequent statements outside that block remain reachable and valid:

for (int i = 0; i < 5; i++) {
    if (i == 2) {
        continue; // Branch taken conditionally
    }
    System.out.println(i); // LEGAL: Reachable when i != 2
}

Systematic Code Tracing Table Methodology

To ensure 100% accuracy on complex 1Z0-811 nested loop questions, construct a structured trace table on your scratch paper tracking variables, conditions, branching jumps, and outputs:

int total = 0;
LOOP_A: for (int a = 1; a <= 2; a++) {
    LOOP_B: for (int b = 1; b <= 3; b++) {
        if (b == 2) {
            continue LOOP_A;
        }
        total += (a * b);
    }
}
System.out.println("Total: " + total);

Trace Table

StepabCondition b == 2Action TakenCurrent total
111falsetotal += (1 * 1)1
212truecontinue LOOP_A (jumps to a++)1
321falsetotal += (2 * 1)3
422truecontinue LOOP_A (jumps to a++)3
53-a <= 2 is falseOuter loop terminatesFinal: 3

The final output printed is Total: 3.

Loading diagram...
Control Flow of Labeled and Unlabeled Branching Statements
Test Your Knowledge

What is the output of the following Java program?

int total = 0;
OUTER: for (int i = 1; i <= 3; i++) {
    INNER: for (int j = 1; j <= 3; j++) {
        if (j == 2) {
            continue OUTER;
        }
        total += (i * j);
    }
}
System.out.println(total);

A
B
C
D
Test Your Knowledge

What is the output of the following code snippet?

int result = 0;
for (int i = 1; i <= 4; i++) {
    for (int j = 1; j <= 4; j++) {
        if (j == 3) {
            break;
        }
        result++;
    }
}
System.out.println(result);

A
B
C
D
Test Your Knowledge

Consider the following code fragment:

int x = 10;
while (x > 0) {
    if (x == 5) {
        break;
        x--;
    }
    x -= 2;
}
System.out.println(x);

A
B
C
D