Java Break

Su Suriya Ravichandran Updated 14 Nov 2026
5 min read ·Lesson 21 of 133

The break statement immediately ends the innermost loop or switch that contains it. Execution jumps to the first statement after that loop or switch. It exists for cases where a loop's natural end condition is not the only reason to stop: the answer has been found, an error has occurred, or the user has asked to quit.

break in a Loop

for (int i = 1; i <= 10; i++) {
    if (i == 5) {
        break;
    }
    System.out.println(i);
}
System.out.println("Loop ended");

Output:

1
2
3
4
Loop ended

When i reaches 5, break exits the loop at once. The println for 5 is never reached, the update i++ does not run, and the condition is not checked again. Control goes straight to "Loop ended".

break works the same way in while and do-while loops.

Stopping a Search Early

The most common use of break is ending a search as soon as the result is known. Checking the remaining elements would waste time and could even give the wrong answer if a later element matched too.

int[] ids = {104, 221, 387, 450, 512};
int target = 387;
int foundAt = -1;

for (int i = 0; i < ids.length; i++) {
    if (ids[i] == target) {
        foundAt = i;
        break;
    }
}

if (foundAt >= 0) {
    System.out.println("Found at index " + foundAt);
} else {
    System.out.println("Not found");
}

Output:

Found at index 2

foundAt starts at -1, a value that cannot be a real index, to signal "not found". If the loop ends normally, no match exists and foundAt is still -1. After the loop, the code inspects foundAt to learn which way the loop ended.

break with while (true)

When the exit decision is made in the middle of the loop body, after some work has been done, a while (true) loop with a break is clearer than contorting the condition:

Scanner sc = new Scanner(System.in);
int total = 0;

while (true) {
    System.out.print("Enter a number (0 to finish): ");
    int n = sc.nextInt();
    if (n == 0) {
        break;
    }
    total += n;
}
System.out.println("Total: " + total);

The number must be read before deciding whether to stop, so the check cannot sit at the top of the loop. Every while (true) loop must have a reachable break, return, or throw; otherwise it never ends.

break in switch

In the traditional colon form of switch, break stops execution from falling through into the next case:

switch (option) {
    case 1:
        System.out.println("New file");
        break;
    case 2:
        System.out.println("Open file");
        break;
    default:
        System.out.println("Unknown");
}

Without the break after case 1, choosing option 1 would print both "New file" and "Open file". The arrow form (case 1 -> ...) never falls through and needs no break.

A break inside a switch exits only the switch, not a loop around it:

while (running) {
    switch (command) {
        case "stop":
            running = false;
            break;          // leaves the switch; the loop then checks running
        case "skip":
            break;          // leaves the switch only; the loop continues
    }
}

To leave the loop from inside such a switch, change the loop condition as shown, use a labeled break, or return from the method.

break Only Exits One Level

In nested loops, a plain break ends only the innermost loop:

for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 3; j++) {
        if (j == 2) {
            break;
        }
        System.out.println(i + "," + j);
    }
}

Output:

1,1
2,1
3,1

Each time j reaches 2, the inner loop ends, but the outer loop continues with the next i.

Labeled break

To leave several levels at once, label the outer loop and name it in the break:

int[][] grid = {
    {4, 8, 15},
    {16, 23, 42},
    {7, 9, 11}
};
int target = 23;
int row = -1, col = -1;

search:
for (int r = 0; r < grid.length; r++) {
    for (int c = 0; c < grid[r].length; c++) {
        if (grid[r][c] == target) {
            row = r;
            col = c;
            break search;
        }
    }
}

System.out.println("Found at row " + row + ", column " + col);

Output:

Found at row 1, column 1

search: attaches a label to the outer for. break search; exits that labeled loop entirely, skipping the rest of both loops. Labels follow identifier rules and are written before the statement with a colon.

An alternative that is often cleaner is to move the search into its own method and return as soon as the result is found. A return leaves every loop in the method at once, and the method name documents what the loops do:

static int[] find(int[][] grid, int target) {
    for (int r = 0; r < grid.length; r++) {
        for (int c = 0; c < grid[r].length; c++) {
            if (grid[r][c] == target) {
                return new int[]{r, c};
            }
        }
    }
    return null;
}

break Versus return Versus continue

StatementEffect
breakLeaves the innermost loop or switch; continues after it
break labelLeaves the labeled statement
continueSkips the rest of the current iteration; the loop goes on
returnLeaves the whole method, including every loop inside it

Practical Example: Validating a Batch Upload

import java.util.List;

public class BatchValidator {
    public static void main(String[] args) {
        List<String> rows = List.of(
            "1001,Ada,ada@example.com",
            "1002,Linus,linus@example.com",
            "1003,Grace",
            "1004,Alan,alan@example.com"
        );

        int validRows = 0;
        String error = null;

        for (int i = 0; i < rows.size(); i++) {
            String[] fields = rows.get(i).split(",");
            if (fields.length != 3) {
                error = "Row " + (i + 1) + ": expected 3 fields, found " + fields.length;
                break;
            }
            validRows++;
        }

        if (error != null) {
            System.out.println("Upload rejected. " + error);
        } else {
            System.out.println("All " + validRows + " rows valid.");
        }
    }
}

Output:

Upload rejected. Row 3: expected 3 fields, found 2

The batch must be all valid or rejected entirely, so the first bad row is enough to decide. break stops checking at that row, and the error message records exactly where it happened. Row 4 is never examined. This "fail fast" pattern is common in import tools and form validation, where reporting the first problem quickly is more useful than scanning the rest.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining
Ask about this post
AI Ask about this post

Ask questions about Java Break and get answers drawn from it.

Signed-in readers only.