Break, Continue, and Labels in Java
Learn when to use Java break and continue, how labels control nested loops, and when extracting a search into a method with an early return reads more clearly.
Learn when to use Java break and continue, how labels control nested loops, and when extracting a search into a method with an early return reads more clearly.
Break, Continue, and Labels in Java
Java’s break exits a loop or switch, and continue skips to the next iteration of a loop. A label lets either statement target an outer loop when nested loops need to stop or advance together.
Introduction
In a nested loop, an unlabeled break exits only the innermost loop. If a search finds its target, a labeled break can exit the outer loop too. Another option is to put the search in a helper method and return the result as soon as it is found; that can make the search easier to test and reuse.
Put a label before the loop it names, such as search: for (...). From a nested loop, break search; exits that loop and continues after it. continue search; skips to the next iteration of the labeled loop. Labels can make a short search easier to follow, but a helper method may be clearer when it can return the result directly.
Labels can name statements other than loops, but continue label must target a loop. That distinction matters when a label is used with a block.
When to Use / Not to Use
Use break when:
- Exiting a loop early based on a condition
- Exiting a traditional switch statement
- Exiting infinite loops
- Stopping search loops when target is found
Use continue when:
- Skipping the rest of the current iteration based on a condition
- Filtering items in processing loops
- Avoiding deeply nested if-else in loop bodies
Use labeled break when:
- Exiting from nested loops to outer scope
- Breaking out of specific loops in multi-nested scenarios
- Implementing early exit from complex nested loop structures
Use labeled continue when:
- Continuing a specific outer loop from within a nested loop
Do not use these when:
- They create unclear control flow (consider extracting to methods)
- Break/continue replace proper loop conditions
- Labels make code harder to understand (consider refactoring)
Diagram: Break and Continue
flowchart TD
A["Loop start"] --> B{"Condition?"}
B -->|false| Z["Exit loop"]
B -->|true| C["Body begins"]
C --> D{"Inner condition?"}
D -->|break| Z
D -->|continue| B
Diagram: Labeled Break and Continue
flowchart TD
E["Outer loop"] --> F{"Outer condition?"}
F -->|false| Y["Exit outer loop"]
F -->|true| G["Inner loop"]
G --> H{"Inner condition?"}
H -->|break outer| Y
H -->|continue outer| F
G --> F
Code Snippet: Control Flow Patterns
public class BreakContinueLabelsDemo {
public static void main(String[] args) {
// Basic break - exit loop early
System.out.println("Basic break:");
for (int i = 0; i < 10; i++) {
if (i == 5) {
System.out.println("Breaking at " + i);
break;
}
System.out.print(i + " ");
}
System.out.println("\n");
// Basic continue - skip iteration
System.out.println("Skip even numbers:");
for (int i = 0; i < 8; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
System.out.print(i + " "); // Prints: 1 3 5 7
}
System.out.println("\n");
// Labeled break - exit nested loop
System.out.println("Labeled break (search):");
int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int target = 5;
search:
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 + " at [" + row + "][" + col + "]");
break search; // Exit both loops
}
}
}
// Labeled continue - continue outer loop
System.out.println("\nLabeled continue (skip rows):");
outer:
for (int row = 0; row < 4; row++) {
for (int col = 0; col < 4; col++) {
if (col == 2 && row == 1) {
System.out.print("X ");
continue outer; // Continue outer loop, skip col 2 for row 1
}
System.out.print(matrix[row % 3][col] + " ");
}
System.out.println();
}
// Break in while loop
System.out.println("\nBreak in while:");
int count = 0;
while (true) {
System.out.print(count + " ");
count++;
if (count >= 5) {
System.out.println("Breaking infinite while");
break;
}
}
// Continue in do-while
System.out.println("\nContinue in processing:");
int num = 0;
do {
num++;
if (num % 2 == 0) {
continue; // Skip even numbers
}
System.out.print(num + " ");
} while (num < 10);
System.out.println();
// Real-world example: validation with early exit
System.out.println("\nValidation loop:");
String[] inputs = {"valid", "INVALID", "also valid", ""};
boolean allValid = true;
for (String input : inputs) {
if (input == null || input.isEmpty()) {
System.out.println("Empty/null input found, rejecting");
allValid = false;
break;
}
if (input.equals("INVALID")) {
System.out.println("Invalid value found, rejecting");
allValid = false;
break;
}
}
System.out.println("All valid: " + allValid);
}
}
Nested Loop Trace: Labeled Break or Early Return
This search visits the matrix row by row. When it finds 3 at [1][0], break search; exits both loops. The element at [1][1] is never checked.
public class LabeledSearchTrace {
public static void main(String[] args) {
int[][] matrix = {{1, 2}, {3, 4}};
int target = 3;
int foundRow = -1;
int foundCol = -1;
search:
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[row].length; col++) {
if (matrix[row][col] == target) {
foundRow = row;
foundCol = col;
break search;
}
}
}
System.out.printf("Found at [%d][%d]%n", foundRow, foundCol);
}
}
The traversal is [0][0] (1), [0][1] (2), then [1][0] (3). The labeled break leaves the search loop immediately, so [1][1] is skipped.
The program prints:
Found at [1][0]
Extracting the search into a method is another option. Its return exits the method, so the caller can use the result directly:
public class SearchWithEarlyReturn {
static int[] find(int[][] matrix, int target) {
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[row].length; col++) {
if (matrix[row][col] == target) {
return new int[] {row, col};
}
}
}
return null;
}
public static void main(String[] args) {
int[][] matrix = {{1, 2}, {3, 4}};
int[] position = find(matrix, 3);
if (position == null) {
System.out.println("Not found");
} else {
System.out.printf("Found at [%d][%d]%n", position[0], position[1]);
}
}
}
Use the label when the surrounding method still has work to do after the loop. Extract a method when the search has a useful result or deserves its own name and tests.
Failure Scenarios
| Scenario | Problem | Solution |
|---|---|---|
| Labeled break without matching label | Compile error | Ensure label exists in scope |
| Continue after break in same loop | Unreachable code | Review control flow |
| Nested break without label | Only exits inner loop | Use labeled break for outer |
Trade-off Table
| Control | Scope | Use Case |
|---|---|---|
break |
Current loop/switch | Exit loop early |
continue |
Current loop | Skip to next iteration |
break label |
Labeled block | Exit specific nested structure |
continue label |
Labeled loop | Continue specific outer loop |
Observability Checklist
- Log break reasons for debugging loop exits
- Instrument label usage for nested loop navigation
- Add metrics for early exit vs complete iteration
- Monitor continue frequency to detect filtering patterns
- Add integration tests for each exit path
Security Notes
- Break in validation loops: Ensure early exit doesn’t bypass security checks—log all early exits
- Complex control flow: Deep nesting with break/continue can hide security vulnerabilities
- Infinite loops with break: Ensure break conditions can’t be bypassed by external input manipulation
Pitfalls
- Labeled break without matching label: Compile error if the label is not in scope
- Break vs continue confusion:
breakexits the targeted loop;continueskips to its next iteration - Too many labels: Multiple jumps can make loop exits harder to trace
- Unreachable code after continue: Code after
continueon the same path is unreachable
Quick Recap Checklist
- An unlabeled
breakexits the nearest loop or switch;continueskips to the next iteration. - A label names the loop that
break labelexits orcontinue labeladvances. - Trace nested loops to see which iterations a labeled statement skips.
- Consider a helper method and early return when the search result belongs in its return value.
- Use labels only when they make the control flow easier to read.
Interview Questions
Further Reading
- For Loops - Where break/continue are most commonly used
- While and Do-While Loops - Loop control in unknown-count iteration
- Switch Expressions - Switch expression behavior and case syntax
- Method Extraction for Complex Control Flow - Refactoring labeled loops to cleaner methods
- Oracle: Branching Statements - Official documentation on
break,continue, and labeled statements
Conclusion
break exits its target and continue advances to the next iteration. In nested loops, a label makes that target explicit.
For a short search, a labeled break can be easy to follow. If the search has a result the caller needs, a helper method that returns the position may be easier to test and reuse.
These control statements work with for loops and while and do-while loops. For switch-specific behavior, see Java switch expressions.
Category
Related Posts
Abstract Classes in Java: Interfaces and Composition
Compare Java interfaces, abstract classes, and composition, then see when shared state, default methods, or sealed types change the design choice.
Arithmetic Operators in Java: Division, Overflow, Promotion
Compare Java arithmetic with runnable examples of division, negative remainders, overflow, type promotion, and BigDecimal for decimal money.
Java Array Basics: Length, Bounds, Copies, and Resizing
Learn Java arrays through runtime-sized allocation, bounds checks, aliasing, copying, and the fixed length that distinguishes them from ArrayList.