Codectionary / Developer documentation / Java

break and continue

break and continue give fine-grained control over loop execution in Java. break immediately exits the nearest enclosing loop (or switch statement) entirely. continue skips the rest of the current iteration and jumps straight to the loop's next iteration check. Java also supports labeled break/continue, which can target an outer loop from within a nested one.

Syntax

break;\ncontinue;

Examples

Using break

Exiting a loop as soon as a target condition is found.

int[] numbers = {1, 3, 5, 8, 9, 12};

for (int num : numbers) {
    if (num % 2 == 0) {
        System.out.println("Found first even number: " + num);
        break;
    }
    System.out.println(num + " is odd");
}

Using continue

Skipping specific iterations while letting the loop continue.

for (int i = 1; i <= 10; i++) {
    if (i % 2 != 0) {
        continue;  // skip odd numbers
    }
    System.out.println(i);  // prints only even numbers
}

Labeled break in Nested Loops

Using a label to break out of an outer loop directly from within an inner one.

outerLoop:
for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 3; j++) {
        if (i == 2 && j == 2) {
            break outerLoop;  // exits BOTH loops, not just the inner one
        }
        System.out.println("i=" + i + ", j=" + j);
    }
}

Best practices

  • Use break to stop a loop as soon as further iteration is pointless, avoiding wasted work
  • Use labeled break/continue sparingly - they are powerful for nested loops but can make control flow harder to follow if overused
  • Prefer restructuring logic into a separate method with an early return over deeply nested labeled breaks when possible
  • Use continue to skip invalid items cleanly instead of wrapping the rest of the loop body in a large if block

Runtime & versions

Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Java Language Specification

Specifications & further reading