Java Break

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

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 Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

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

Signed-in readers only.