Java break, continue and Labeled Statements
Exit loops early with break, skip to the next iteration with continue, and escape nested loops with labeled break and labeled continue. Covers why Java has no goto, labeled blocks, how continue behaves in for loops, and cleaner alternatives such as extracting a method.
kvi5hnuCode Sprout team member8 min readOn this page
Loops normally end when their condition becomes false. Sometimes it's more natural to leave a loop from the middle, or to skip the rest of the current pass. Java provides two statements for this:
breakleaves the loop (orswitch) immediately.continueskips the rest of the current iteration and goes on with the next one.
Both have labeled forms that work across nested loops.

Why No goto?
goto lets a program jump to any labeled line. It's been considered poor style since Edsger Dijkstra's 1968 letter "Go To Statement Considered Harmful": unrestricted jumps produce tangled "spaghetti code". Java's designers left it out of the language, though goto is a reserved word, so you can't use it as a name.
Not everyone agreed that all jumps are evil. Donald Knuth's article "Structured Programming with go to Statements" argued that some disciplined jumps, like leaving a loop early, make code clearer. Java's designers agreed with that much, so Java has break and continue, including labeled versions that can exit several nested loops. These are structured jumps: they only move forward out of a block or to the next iteration of a loop, never to an arbitrary place.
break: Leave the Loop
You've already seen break end a classic switch case. The same statement ends the innermost enclosing loop:
while (months <= 60) {
saved += deposit;
saved += saved * ratePercent / 100;
if (saved >= target) break;
months++;
}
This loop (the savings example from the loops article, capped at five years) has two exits: months > 60 when the condition is checked at the top, or saved >= target partway through the body.
You could write it without break:
while (months <= 60 && saved < target) {
saved += deposit;
saved += saved * ratePercent / 100;
if (saved < target) {
months++;
}
}
Now saved < target appears twice. One camp uses break to avoid repeating the test; the other prefers loops whose only exit is the condition at the top. Both are acceptable. Choose whichever makes the logic clearer.
A typical use: "loop and a half"
When you must do some work before you can decide whether to continue, a while (true) loop with a break in the middle is a common idiom:
Scanner in = new Scanner(System.in);
int sum = 0;
while (true) {
System.out.print("Enter a number (0 to stop): ");
int n = in.nextInt();
if (n == 0) break;
sum += n;
}
System.out.println("Sum: " + sum);
continue: Skip to the Next Iteration
continue ends the current pass and jumps back to the loop's header:
while (total < budget) {
System.out.print("Item price: ");
price = in.nextInt();
if (price < 0) continue;
total += price; // skipped for a negative price
}
For a negative price, the rest of the body is skipped and control goes straight back to total < budget.
In a for loop, continue jumps to the update part (then the condition), so the counter still advances:
for (item = 1; item <= 20; item++) {
System.out.print("Price of item " + item + " (negative to skip): ");
price = in.nextInt();
if (price < 0) continue;
total += price; // skipped for a negative price
}
After continue, item++ still runs. This is where a for loop and its "equivalent" while loop differ: in a hand-written while loop with item++ at the end of the body, continue would skip the increment, and the loop could run forever.
public class Solution {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) continue;
if (i > 7) break;
System.out.print(i + " ");
}
System.out.println();
int sum = 0;
int[] input = {5, -3, 10, -1, 7};
for (int n : input) {
if (n < 0) continue;
sum += n;
}
System.out.println("sum of non-negatives: " + sum);
}
}
1 3 5 7
sum of non-negatives: 22
Trace the first loop: even numbers are skipped by continue; 1, 3, 5, 7 are printed; at 8, continue skips it; at 9, i > 7 triggers break.
Labeled break: Escape Nested Loops
An unlabeled break exits only the innermost loop. To leave several nested loops at once, put a label (an identifier followed by a colon) in front of the outer loop, and write break label;:
public class Solution {
public static void main(String[] args) {
int[][] grid = {
{1, 2, 3},
{4, -5, 6},
{7, 8, 9}
};
int foundRow = -1;
int foundCol = -1;
search:
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[r].length; c++) {
if (grid[r][c] < 0) {
foundRow = r;
foundCol = c;
break search;
}
}
}
if (foundRow >= 0) {
System.out.println("negative at " + foundRow + "," + foundCol);
} else {
System.out.println("no negative values");
}
}
}
negative at 1,1
(grid is a two-dimensional array, covered in the arrays articles. Here, just read it as a 3 × 3 table.)
Points to notice:
- The label goes immediately before the loop it names (
search:), andbreak search;jumps to the first statement after that loop. - As with any
break, the code after the loop often needs to know how the loop ended (normally, or bybreak). HerefoundRowtells us. - Labels follow the usual identifier rules. By convention they're short lowercase words such as
outer,searchorreadData.
Labeled continue
continue label; jumps to the next iteration of the labeled loop, abandoning the rest of the inner loop and the outer body:
public class Solution {
public static void main(String[] args) {
outer:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (j == 2) continue outer;
System.out.print(i + "" + j + " ");
}
}
System.out.println();
}
}
11 21 31
As soon as j reaches 2, control jumps to the outer loop's update (i++), so only j == 1 is ever printed.
Labels on Any Statement
Curiously, a label can be attached to any statement, including a plain block or an if. Then break label; exits that block:
check: {
if (sum > 10) break check;
System.out.println("not printed when sum > 10");
}
// execution resumes here after break check
This can simulate a forward goto, as long as there's a block that ends just before the place you want to jump to. Use it rarely: it's legal, but unusual enough to surprise readers. Also note that you can only jump out of a block, never into one, and continue only works with labels on loops.
Alternatives: Often Clearer
break and continue are optional: you can always express the same logic without them, with flags or modified conditions. Some programmers avoid them entirely. The cleanest alternative for "search nested loops and stop" is usually to extract a method and return:
static int[] findNegative(int[][] grid) {
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[r].length; c++) {
if (grid[r][c] < 0) return new int[] {r, c};
}
}
return null; // not found
}
return exits all loops at once, the method name documents what the loops do, and the "how did it end?" question is answered by the return value. Methods are covered in detail in the classes part.
Common questions
Does break inside a switch inside a loop exit the loop?
In a classic colon-style switch, an unlabeled break exits only the switch, and the loop continues. To leave the loop from inside the switch, use a labeled break on the loop, or return. In an arrow-form switch statement, break isn't needed for the cases, but a break written there also exits only the switch.
Is a labeled break the same as goto?
No. It can only jump forward, to the end of an enclosing labeled statement, and never into a block or backward to an arbitrary place. This keeps control flow structured: the reader knows exactly where execution continues.
Can continue be used in a switch?
Only when the switch is inside a loop. Then continue skips to the next iteration of that loop. Inside a switch expression, continue is a compile error.
Should I avoid break and continue completely?
No. A break in a search loop and a continue guard at the top of a loop body are clear, idiomatic code. Avoid them deep inside long loop bodies, where they are easy to overlook, and consider extracting a method instead of using labels.
Do streams have a break equivalent?
Partly. takeWhile (Java 9), findFirst, anyMatch and limit stop a stream early, but there is no general break or continue inside forEach. If you need complex early exits, a plain loop is usually clearer than a stream.
Summary
breakexits the innermost loop orswitch;continueskips to the next iteration of the innermost loop.- In a
forloop,continuestill runs the update expression; in awhileloop, it jumps straight to the condition. - Labeled
break label;exits the labeled statement (typically an outer loop);continue label;starts the next iteration of the labeled loop. - Java has no
goto(it's a reserved word); labeled jumps only move out of blocks, never into them. - After a
break, check how the loop ended. Often, extracting a method withreturnis the clearest alternative.
Practice Questions
What does this print? for (int i = 0; i < 5; i++) { if (i == 3) break; System.out.print(i); }
012. When i reaches 3, the loop ends before printing.
And this? for (int i = 0; i < 5; i++) { if (i == 3) continue; System.out.print(i); }
0124. Only the pass with i == 3 is skipped; the loop continues with 4.
Why can this loop run forever? int i = 0; while (i < 10) { if (i % 2 == 0) continue; System.out.println(i); i++; }
When i is 0 (even), continue jumps back to the condition without executing i++, so i stays 0 forever. In a for loop, the update would still run. Fix it by incrementing before the continue, or by using a for loop.
In nested loops over rows and columns, how do you stop both loops as soon as a target value is found?
Label the outer loop and use a labeled break: outer: for (...) { for (...) { if (found) break outer; } }. Alternatively, move the loops into a method and return when the value is found.
Is goto valid in Java?
No. goto is a reserved keyword (as is const), so it can't be used as an identifier, but it has no function in the language. Use structured statements, break/continue (optionally labeled), or return.
Previous: The Java switch Statement: Four Forms of switch and Fall-Through
Next: Java BigInteger and BigDecimal: Arbitrary-Precision Arithmetic
Related reading

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.