break and continue statement in Java
-
Last Updated: November 2, 2023
-
By: javahandson
-
Series
Learn Java in a easy way
In this article, we will learn the break and continue statement in Java with simple, hands-on examples. Both keywords change how a loop runs. One walks out of the loop early, and the other skips ahead to the next round. If you want to learn about other Java topics you can click the above Java menu or you can click on this link Java topics.
Loops repeat work for us. Sometimes, though, we need to bend that repetition. Maybe we found what we were looking for and there is no point in checking the rest. Maybe one bad record should be ignored while the good ones keep flowing.
Java gives us two small keywords for exactly these moments: break and continue.
Think of a loop as reading a stack of job applications. A break is you finding the perfect candidate, closing the folder, and walking away. A continue is you spotting a blank form, tossing it aside, and reaching straight for the next one.
break exits a loop early, and how it stops fall-through in a switch.continue skips the rest of the current iteration.Keep this one line in your head for the rest of the article.
Everything else is a detail on top of those two sentences.
A break statement ends the nearest enclosing loop or switch block immediately. Control jumps to the first statement after that block. Any iterations that were still pending never happen.
package com.java.handson.control.statements;
public class BreakDemo {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break;
}
System.out.println("iteration number : " + i);
}
System.out.println("Control is outside of the for loop");
}
}
// Output:
// iteration number : 1
// iteration number : 2
// iteration number : 3
// iteration number : 4
// Control is outside of the for loopThe loop was written to run ten times. It only ran four.
When i reaches 5, the if condition matches and break fires. Notice that 5 itself never gets printed. The break runs before the print statement, so the whole rest of that iteration is abandoned along with the loop.
Searching is where break earns its keep. Once you have found your value, scanning the remaining elements is wasted work.
package com.java.handson.control.statements;
public class SearchDemo {
public static void main(String[] args) {
int[] numbers = {4, 9, 15, 22, 31};
int target = 15;
int foundAt = -1;
int i = 0;
while (i < numbers.length) {
if (numbers[i] == target) {
foundAt = i;
break;
}
i++;
}
System.out.println("Found " + target + " at index : " + foundAt);
}
}
// Output:
// Found 15 at index : 2Our array holds five numbers, but the loop stops after three checks. That is the whole point.
A classic switch block does something surprising. Once a case matches, execution falls straight through into the cases below it. A break is what stops that.
package com.java.handson.control.statements;
public class SwitchDemo {
public static void main(String[] args) {
String colour = "blue";
switch (colour) {
case "red":
System.out.println("It is red");
break;
case "blue":
System.out.println("It is blue");
break;
default:
System.out.println("No colour");
}
System.out.println("Control is outside of the switch block");
}
}
// Output:
// It is blue
// Control is outside of the switch blockNow delete that break from the "blue" case and run it again.
switch (colour) {
case "red":
System.out.println("It is red");
break;
case "blue":
System.out.println("It is blue"); // no break here
default:
System.out.println("No colour");
}
// Output:
// It is blue
// No colourJava printed “No colour” even though the colour clearly matched blue. Execution fell through into default. Forgetting a break here is one of the oldest bugs in the language.
Java 14 fixed this properly with arrow labels. An arrow case never falls through, so no break is needed at all.
String colour = "blue";
switch (colour) {
case "red" -> System.out.println("It is red");
case "blue" -> System.out.println("It is blue");
default -> System.out.println("No colour");
}
// Output:
// It is bluePrefer the arrow form in new code. You get the same behaviour with less ceremony and one less way to slip.
A continue statement skips the rest of the current iteration and jumps to the next one. The loop stays alive. Only this single pass gets cut short.
package com.java.handson.control.statements;
public class ContinueDemo {
public static void main(String[] args) {
for (int i = 1; i < 10; i++) {
if (i == 4 || i == 6 || i == 8) {
continue;
}
System.out.println("Iteration number : " + i);
}
}
}
// Output:
// Iteration number : 1
// Iteration number : 2
// Iteration number : 3
// Iteration number : 5
// Iteration number : 7
// Iteration number : 9Values 4, 6 and 8 never reach the print statement. Every other value does, and the loop still runs to completion.
Here is the detail people miss. In a for loop, continue does not skip the update expression. Java still runs i++ before the next iteration begins. Without that guarantee, the loop would never advance.
That guarantee disappears the moment you move to a while loop, where you increment the counter yourself. Look closely at this code and try to spot the bug.
int i = 0;
while (i < 5) {
if (i == 2) {
continue; // BUG: i is never incremented
}
System.out.println(i);
i++;
}
// Output:
// 0
// 1
// ...and then it hangs foreverWhen i becomes 2, continue jumps back to the condition. But i++ sits below the continue, so it never executes. The value of i is stuck at 2 forever, the condition stays true, and your program spins until you kill it.
Fix it by incrementing before you skip, or simply reach for a for loop instead.
| Point | break | continue |
|---|---|---|
| What it ends | The whole loop | Only the current iteration |
| Where control goes | First statement after the loop | Back to the loop condition |
| Remaining iterations | Cancelled | Still run |
| Allowed in a switch | Yes, and it stops fall-through | No, it is a compile error |
| Works with labels | Yes | Yes |
| Typical use | Stop once you find a match | Skip records that fail a check |
One loop, one condition, one keyword swapped. Watch what changes.
// With break
for (int i = 1; i <= 5; i++) {
if (i == 3) {
break;
}
System.out.print(i + " ");
}
// Output: 1 2
// With continue
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
System.out.print(i + " ");
}
// Output: 1 2 4 5The first loop quits at 3. The second one merely steps over 3 and carries on to 5. Read those two outputs again and the difference will stick.
By default, both keywords act on the nearest enclosing loop. Inside a nested loop, a plain break only escapes the inner loop, and the outer loop happily starts its next round.
What if you want to escape both? That is what labels are for. A label is just a name you stick on a loop, followed by a colon.
package com.java.handson.control.statements;
public class LabeledBreakDemo {
public static void main(String[] args) {
int[][] grid = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int target = 5;
outer:
for (int row = 0; row < grid.length; row++) {
for (int col = 0; col < grid[row].length; col++) {
if (grid[row][col] == target) {
System.out.println("Found " + target + " at row " + row + ", column " + col);
break outer;
}
System.out.println("Checked " + grid[row][col]);
}
}
System.out.println("Search finished");
}
}
// Output:
// Checked 1
// Checked 2
// Checked 3
// Checked 4
// Found 5 at row 1, column 1
// Search finishedWe named the outer loop outer. Writing break outer; abandons both loops at once and lands on the “Search finished” line.
Had we written a plain break instead, only the inner loop would stop. The outer loop would move to row 2 and keep scanning numbers we no longer care about.
package com.java.handson.control.statements;
public class LabeledContinueDemo {
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.println("i = " + i + ", j = " + j);
}
}
}
}
// Output:
// i = 1, j = 1
// i = 2, j = 1
// i = 3, j = 1Each time j hits 2, continue outer; abandons the inner loop entirely and bumps i to its next value. The inner loop never gets past j = 1.
Labels are powerful, but use them sparingly. A method with three labels is usually a method that wants to be broken into smaller methods.
continue belongs to loops only.break leaves a loop, not a method. Use return for that.Let us put both keywords in one small program. We will scan a list of orders and add them to a running total. Invalid orders get skipped. The first order that blows the budget stops the scan.
package com.java.handson.control.statements;
public class OrderScanner {
public static void main(String[] args) {
int[] orders = {120, -5, 340, 0, 90, 1200, 250};
int budget = 1000;
int spent = 0;
for (int i = 0; i < orders.length; i++) {
int amount = orders[i];
if (amount <= 0) {
System.out.println("Skipping invalid order at index " + i + " : " + amount);
continue;
}
if (amount > budget) {
System.out.println("Order " + amount + " is over budget. Stopping.");
break;
}
spent = spent + amount;
System.out.println("Accepted order " + amount + ". Running total : " + spent);
}
System.out.println("Final total : " + spent);
}
}
// Output:
// Accepted order 120. Running total : 120
// Skipping invalid order at index 1 : -5
// Accepted order 340. Running total : 460
// Skipping invalid order at index 3 : 0
// Accepted order 90. Running total : 550
// Order 1200 is over budget. Stopping.
// Final total : 550Trace it slowly. The -5 and the 0 are junk, so continue throws them away and the scan rolls on. The 1200 is a hard stop, so break ends the loop there and then.
Notice what never got touched. The final order of 250 sits in the array, unread. Our loop walked away before reaching it, and that is exactly the behaviour we asked for.
This shape appears constantly in real code. Skip the bad rows, stop on the fatal one.
A: A break statement ends the entire loop, so no further iterations run. A continue statement ends only the current iteration, and the loop moves on to the next one.
A: No. The compiler rejects it. A continue statement works only inside a loop. A break statement, on the other hand, is valid in both a loop and a switch.
A: No. Java still runs the update expression such as i++ before the next iteration. That is why continue is safe in a for loop but risky in a while loop, where you increment the counter yourself.
A: Only with a label. A plain break exits the nearest enclosing loop. Label the outer loop and write break outerLabel; to escape both loops in one go.
A: Control leaves the loop the moment break runs, so any statement written directly after it can never execute. Java treats that as a compile-time error rather than a warning.
A: No. Arrow labels, added in Java 14, never fall through to the next case. Only the classic colon-style switch needs a break to stop fall-through.
Let us wrap up what we covered.
Both keywords bend the flow of a loop, and one sentence separates them. A break walks out of the loop. A continue walks out of the current iteration.
Use break when you have found what you came for, or when carrying on would be wrong. Use continue when a single item does not deserve the rest of the loop body. Inside a switch, break pulls double duty by stopping fall-through, though the arrow syntax now handles that for you.
Watch the two traps. A missing break in a colon-style switch prints cases you never wanted. A continue placed above the increment in a while loop will hang your program outright.
Open your editor and run these snippets. Change a value, swap a keyword, and read the output. Ten minutes of that beats an hour of reading.