Question
I have a nested loop in Java like this:
for (Type type : types) {
for (Type t : types2) {
if (someCondition) {
// Do something and then stop looping
break; // This only breaks the inner loop
}
}
}
How can I break out of both loops?
I have looked at similar questions, but many of the solutions use goto, which Java does not support in that way. I also do not want to:
- move the inner loop into a separate method
- use
returnto exit from the surrounding method
I want to stop executing the nested loop block entirely when the condition is met.
Short Answer
By the end of this page, you will understand how break works in nested loops in Java, how to exit multiple loops using a labeled break, and when alternatives like boolean flags or early return are more appropriate.
Concept
In Java, a normal break statement only exits the nearest enclosing loop or switch. In a nested loop, that means it stops only the inner loop.
When you need to stop both the inner and outer loop, Java gives you a feature called a labeled break. A label is a name placed before a loop. You can then write break labelName; to exit that specific loop, even if you are currently inside a deeper nested loop.
This matters because nested loops are common in real programs:
- searching through combinations of values
- comparing items from two collections
- scanning rows and columns in a grid
- stopping as soon as a match is found
Without a clear way to exit multiple loops, code can become messy, slow, or harder to read. Java's labeled break is the direct language feature for this situation.
Mental Model
Think of nested loops like walking through a building:
- the inner loop is the current room
- the outer loop is the whole floor
A normal break says: leave this room.
A labeled break says: leave this floor.
So if you are deep inside a nested structure and want to stop the whole process, a labeled break lets you jump out to the exact loop you named.
Syntax and Examples
Basic break
A normal break exits only the nearest loop:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (j == 1) {
break;
}
System.out.println(i + "," + j);
}
}
Here, break stops only the inner for loop.
Labeled break
To break out of both loops, add a label to the outer loop:
outerLoop:
for (Type type : types) {
for (Type t : types2) {
if (someCondition) {
// Do something
break outerLoop;
}
}
}
How it works
outerLoop:is a label attached to the outer loop.
Step by Step Execution
Consider this code:
outer:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.println("i=" + i + ", j=" + j);
if (i == 2 && j == 2) {
break outer;
}
}
}
System.out.println("Done");
Step by step
- The label
outer:is attached to the outerforloop. i = 1starts.- Inner loop runs with
j = 1,j = 2, andj = 3. - Then
i = 2starts. - Inner loop runs with
j = 1. - Then
j = 2. - The condition
i == 2 && j == 2becomes true.
Real World Use Cases
Nested loop exits appear in many practical situations:
Searching for the first match
outer:
for (String username : usernames) {
for (String banned : bannedNames) {
if (username.equals(banned)) {
System.out.println("Blocked user found: " + username);
break outer;
}
}
}
Scanning a 2D grid
int[][] board = {
{0, 0, 0},
{0, 1, 0},
{0, 0, 0}
};
find:
for (int row = 0; row < board.length; row++) {
for (int col = 0; col < board[row].length; col++) {
if (board[row][col] == 1) {
System.out.println("Found at row " + row + ", col " + col);
break find;
}
}
}
Comparing two collections until a duplicate is found
Real Codebase Usage
In real Java codebases, developers usually choose among these patterns:
1. Labeled break for immediate loop exit
Good when:
- you are inside nested loops
- stopping both loops is the clearest option
- the logic is local and easy to follow
search:
for (Order order : orders) {
for (Item item : order.getItems()) {
if (item.getId().equals(targetId)) {
foundItem = item;
break search;
}
}
}
2. Guard variables when labels feel unclear
Some teams avoid labels for readability reasons and use a boolean flag instead.
boolean shouldStop = false;
for (Order order : orders) {
for (Item item : order.getItems()) {
if (item.getId().equals(targetId)) {
foundItem = item;
shouldStop = true;
break;
}
}
if (shouldStop) {
break;
}
}
3. Early return from a method
This is often the cleanest option when the loop is inside a method whose job is to find or process something.
public Item findItem {
(Order order : orders) {
(Item item : order.getItems()) {
(item.getId().equals(targetId)) {
item;
}
}
}
;
}
Common Mistakes
Mistake 1: Expecting break to exit all loops
Broken example:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i == 1 && j == 1) {
break;
}
}
}
This exits only the inner loop.
Fix
Use a labeled break if you want to stop the outer loop too:
outer:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i == 1 && j == 1) {
break outer;
}
}
}
Mistake 2: Putting the label in the wrong place
Broken example:
Comparisons
| Approach | Exits inner loop only | Exits outer loop too | Exits method | Best when |
|---|---|---|---|---|
break | Yes | No | No | You only want to stop the current loop |
break label; | Yes | Yes | No | You want to stop a specific outer loop |
| Boolean flag | Yes | Yes, with extra checks | No | You want to avoid labels |
return | Yes | Yes | Yes | The method should end immediately |
Cheat Sheet
// Normal break: exits nearest loop only
break;
// Labeled break: exits the named outer loop
outer:
for (...) {
for (...) {
if (condition) {
break outer;
}
}
}
Rules
- A plain
breakexits only the closest enclosing loop orswitch. - A labeled
breakexits the loop with that label. - The label must appear before the loop statement.
- Java does not use
gotofor this. - After
break label;, execution continues after the labeled loop.
Good label names
outersearchscanGridfindMatch
Alternative pattern
boolean found = false;
for (...) {
(...) {
(condition) {
found = ;
;
}
}
(found) {
;
}
}
FAQ
How do you break out of two nested loops in Java?
Use a labeled break:
outer:
for (...) {
for (...) {
if (condition) {
break outer;
}
}
}
Does Java support goto for breaking loops?
No. Java reserves the word goto, but it is not used as a control-flow statement. Use labeled break or continue instead.
Is labeled break bad practice in Java?
Not necessarily. It is acceptable when it clearly solves a nested-loop exit problem. Overusing labels can hurt readability, but a single well-named label is often fine.
What is the difference between break and return in Java?
break exits a loop or switch. return exits the entire method.
Can I use continue with labels in Java?
Yes. continue label; skips to the next iteration of the labeled loop.
Mini Project
Description
Build a small Java program that searches a seating chart for the first reserved seat. This demonstrates how to stop scanning a two-dimensional structure as soon as a match is found, which is a common use case for breaking out of nested loops.
Goal
Create a program that searches a 2D array and stops both loops immediately when the first target value is found.
Requirements
- Create a 2D array representing a seating chart or grid.
- Use nested loops to scan through each row and column.
- Stop both loops as soon as the target value is found.
- Print the location of the found item.
- Print a message if the target value does not exist.
Keep learning
Related questions
Avoiding Java Code in JSP with JSP 2: EL and JSTL Explained
Learn how to avoid Java scriptlets in JSP 2 using Expression Language and JSTL, with examples, best practices, and common mistakes.
Choosing a @NotNull Annotation in Java: Validation vs Static Analysis
Learn how Java @NotNull annotations differ, when to use each one, and how to choose between validation, IDE hints, and static analysis tools.
Convert a Java Stack Trace to a String
Learn how to convert a Java exception stack trace to a string using StringWriter and PrintWriter, with examples and common mistakes.