The order list with surprises
Riya is adding up the day's canteen orders from a list. Some entries are mistakes: −5 and 0. One entry is ₹9,99,999, clearly someone's finger slipped. She wants to skip the mistakes, and stop completely at the suspicious one so a human can check it.
Sir, can I skip just the bad entries but still finish the list? And separately, stop everything when something looks like fraud?
Two keywords. continue means “skip the rest of this round, go to the next one”. break means “leave the loop right now”. Both are just jumps behind the screen.
And if the loop is inside another loop?
Then you can put a label on the outer loop and say exactly which loop to break out of. Let's see all three.
What are break and continue?
break terminates the innermost enclosing for, while, do-while or switch statement and transfers control to the statement after it. continue skips the remaining statements of the current iteration of the innermost loop and proceeds with its next iteration (in a for loop, the update runs next; in while/do-while, the condition is checked). With a label (outer: for (…)), break outer; or continue outer; applies to the labelled loop instead.
break = “I'm done with this loop, get out.” continue = “I'm done with this item, move to the next one.” A label is a name tag on a loop, so you can say which loop you mean when loops are nested.
Words you'll meet in this lesson
search: for (…).found.Where each one jumps
| Statement | Jumps to | Typical use |
|---|---|---|
break; | The first statement after the innermost loop or switch | Found it; stop searching |
continue; in for | The update part (i++), then the condition | Skip invalid items |
continue; in while / do-while | The condition | Skip, but beware of skipping your own update |
break label; | After the labelled loop | Leave nested loops at once |
continue label; | The next iteration of the labelled loop | Give up on this outer item |
return; | Out of the whole method | The method's job is done |
Exam tip: break can be used in loops and switch; continue only in loops. Both affect only the innermost loop unless a label is used. Using either outside a loop is a compile error (“break outside switch or loop”).
The four jumps, with typical uses
break
Linear search, stopping at the first match, or stopping when a limit is hit.
Stop earlycontinue
Skip blank lines in a file, refunds in a sales total, or inactive users in a mailing.
Skip onelabelled break
Searching a grid (seats, a chessboard, a matrix) and stopping both loops at the first hit.
Nested loopslabelled continue
“This candidate failed one check; move on to the next candidate” from inside an inner loop.
Nested loopsAlternatives that are often clearer
| Instead of | Consider |
|---|---|
| Labelled break out of deep nesting | Move the loops into a method and use return |
| Many continue statements in one loop | One guard if at the top, or a small helper method isValid(x) |
break + a found flag to answer “is there any…?” | Later: stream().anyMatch(…) (Lesson 14.3) |
Adding skip and stop rules to a loop
Start with the plain loop
Without extra rules, every element is visited and added, including the bad ones.for (int amount : orders) { total += amount; }Skip invalid items with continue, near the top
if (amount <= 0) { continue; }continuecompiles to agotothat jumps to the loop's “next element” step, skipping the rest of the body.Stop on a serious problem with break
if (amount > 50_000) { break; }breakis agototo the first instruction after the loop. The remaining elements are never visited.Remember why the loop ended
After a loop with break, you often need to know: did it finish normally or stop early? Record it in a flag or variable before breaking.
Once execution is past the loop, both exits look the same. Only your variables can tell them apart.Use a label only for nested loops
A label is not a goto target you can jump to from anywhere. It can only name an enclosing loop, andsearch: for (int r = 0; r < rows; r++) { for (int s = 0; s < seats; s++) { if (free(r, s)) { break search; } } }break searchjumps just past that loop.
Skip, skip, stop: both views
Left: the order list being processed. Right: the stack and the jumps in the bytecode.
- 120 is valid, so it's added: total = 120.
- −5 fails the check.
continueskips the rest of the body and moves to the next item. - 340 is valid: total = 460.
- 0 is also invalid: skipped with
continue. - 999999 is over the ₹50,000 limit.
breakends the loop immediately. - The line after the loop runs. The last order, 85, was never visited.
- The for-each loop is compiled with a hidden index
i. Valid amounts reachtotal += amount. continueis agoto STEP: it skips the rest of the body but still runs the update.- Index 2: normal path, total = 460.
- Index 3: another jump to STEP.
breakis agoto END, the first instruction after the loop.- The loop ended at index 4; the element at index 5 was never read.
Stop and skip in real systems
Early exits save time; skips keep bad data from spoiling good results.
Watch it with an example: finding the first free window seat
A train coach's seats are checked one by one. continue skips booked seats; break stops the search as soon as a free window seat is found.
- s = 1: booked.
continuejumps straight to the next round; the rest of the body is skipped. - s = 2: free, but it's a middle seat, so the
breakcondition is false. The loop goes on. - s = 3: booked →
continueagain. - s = 4: free and a window seat.
breakleaves the loop immediately. - Saved work: seats 5 and 6 are never looked at. With 72 seats per coach and many coaches, stopping early matters.
- Result: seat 4 is allotted. Booking systems use this “skip bad ones, stop at the first good one” pattern all the time. (Simplified example.)
1. Searching and stopping at the first match
Checking whether a username is taken, whether any order is unpaid, or finding the first available delivery slot: as soon as the answer is known, break.
2. Skipping bad rows during imports
When importing a CSV of products or students, blank and invalid rows are skipped with continue (and logged), so one bad line doesn't stop the whole import.
3. Seat and slot allocation
Cinema and train booking systems search a grid of rows and seats for a block of free seats. A labelled break (or a method with return) stops both loops once a block is found.
4. Circuit breakers in batch jobs
If a job sees too many failures in a row (for example the database is down), it stops with break instead of failing on every remaining record, and raises an alert.
5. Respecting user preferences
When sending offers, users who unsubscribed or have no verified email are skipped with continue. Getting this wrong is not just annoying; it can break privacy rules.
Examples are simplified. Real systems log every skipped or failed item.
Riya's order processor
public class Main {
public static void main(String[] args) {
int[] orders = {120, -5, 340, 0, 999999, 85};
int total = 0;
for (int amount : orders) {
if (amount <= 0) {
System.out.println("Skipping invalid amount " + amount);
continue; // next order
}
if (amount > 50_000) {
System.out.println("Suspicious amount " + amount + ": stopping");
break; // leave the loop
}
total += amount;
}
System.out.println("Total processed: Rs " + total);
}
}continue;Skipstotal += amountfor invalid amounts and moves to the next order.break;Ends the whole loop. 85 is never processed.- Checks at the topSkip and stop rules come first, like guard clauses; the normal work sits at the bottom.
Follow every skip and the final stop
Watch the tracer jump back to the loop line after each continue, and straight past the loop on break.
Worked examples: real problems, solved and traced in memory
break leaves a loop early; continue skips to the next pass. Both are about not doing unnecessary work. In the traces, watch the JVM jump straight out of the loop, or straight back to its top.
Find the first out-of-stock item
Problem statement
A shop's app checks the stock of 6 items in order and must alert on the first item with zero stock. No need to look further once it's found: use break.
items Rice, Oil, Sugar, Salt, Tea, Dal; stock 40, 12, 0, 25, 0, 8
First out of stock: Sugar (checked 3 items)
Approach
- Loop over the items.
- When stock is 0, remember the item and
break. - After the loop, report what was found (or that all are in stock).
Solution: run it live
What happens in memory, step by step
Recorded from the real JVM: press Next to execute one line at a time. Watch method calls push and pop frames on the stack, and objects (numbered #1, #2 …) appear on the heap.
Total only the delivered orders
Problem statement
Today's orders have statuses. Cancelled orders must be skipped when totalling revenue. Use continue to skip them.
amounts 450, 1200, 300, 800; statuses OK, CANCELLED, OK, OK
Revenue: Rs 1550
Approach
- Loop over the orders.
- If cancelled,
continue: go straight to the next order. - Otherwise add the amount.
Solution: run it live
What happens in memory, step by step
Recorded from the real JVM: press Next to execute one line at a time. Watch method calls push and pop frames on the stack, and objects (numbered #1, #2 …) appear on the heap.
Find a free seat with a labeled break
Problem statement
A small hall has 3 rows of 4 seats (1 = booked, 0 = free). Find the first free seat, searching row by row. A plain break would only leave the inner loop, so use a labeled break to leave both.
rows {1,1,1,1}, {1,1,0,1}, {0,0,0,0}First free seat: B3
Approach
- Label the outer loop
search:. - When a free seat is found, record it and
break search;. - Print the seat as row letter + number.
Solution: run it live
What happens in memory, step by step
Recorded from the real JVM: press Next to execute one line at a time. Watch method calls push and pop frames on the stack, and objects (numbered #1, #2 …) appear on the heap.
Check yourself
Quick revision
Lesson 3.5 in one screen
break: leave the innermost loop or switch now.continue: skip the rest of this iteration (for: go to update; while: go to condition).- Labels:
outer: for (…)→break outer;/continue outer;for nested loops. - break inside a switch only leaves the switch, not the surrounding loop.
- In while loops, continue can skip your own update → infinite loop.
- Behind the screen: both are just
gotojumps. Preferreturnfrom a method for deep exits.
Interview and viva questions
Difference between break and continue?
break terminates the loop (or switch) entirely and continues after it. continue ends only the current iteration and moves on to the next one. continue can't be used in a switch on its own.
Does Java have goto?
goto is a reserved word but not usable. Labelled break and continue cover its legitimate uses (leaving nested loops) in a structured way.
Difference between break and return?
break leaves only the loop or switch; the method continues after it. return leaves the entire method immediately, optionally giving back a value.
Can a label be used on any statement?
Labels can be placed on any statement, but they're only useful on loops (and blocks), because break and continue can only target an enclosing labelled statement.
Are break and continue bad style?
Not in moderation. Early exits often make code simpler. Problems start when a loop has many breaks and continues scattered through it; then extracting a method or using a clear condition is better.
Practice problems
Each problem needs a skip or an early stop. Try them first, then compare with the solution.
First number divisible by 7 and 11
Find the first number greater than 500 that's divisible by both 7 and 11.
start = 500
First match after 500: 539
Show solution and explanation
public class Main {
public static void main(String[] args) {
int start = 500;
int found = -1;
for (int n = start + 1; ; n++) {
if (n % 7 == 0 && n % 11 == 0) {
found = n;
break;
}
}
System.out.println("First match after " + start + ": " + found);
}
}How it works: the loop has no condition (for (… ; ; n++)), so it would run forever, but break ends it at the first match. That's safe here because a multiple of 77 always exists. 539 = 77 × 7.
Skip the multiples of 3
Print the numbers from 1 to 20, skipping multiples of 3.
limit = 20
1 2 4 5 7 8 10 11 13 14 16 17 19 20
Show solution and explanation
public class Main {
public static void main(String[] args) {
int limit = 20;
StringBuilder line = new StringBuilder();
for (int i = 1; i <= limit; i++) {
if (i % 3 == 0) {
continue;
}
if (line.length() > 0) line.append(' ');
line.append(i);
}
System.out.println(line);
}
}How it works: continue skips multiples of 3 before anything is added. A StringBuilder (Lesson 4.6) collects the output so we can put spaces only between numbers.
Add until a negative appears
Readings come from a sensor. Add them up, but stop at the first negative reading (it means the sensor failed).
readings = {12, 15, 9, -1, 20, 18}Sum before failure: 36 (3 readings)
Show solution and explanation
public class Main {
public static void main(String[] args) {
int[] readings = {12, 15, 9, -1, 20, 18};
int sum = 0, count = 0;
for (int r : readings) {
if (r < 0) {
break;
}
sum += r;
count++;
}
System.out.println("Sum before failure: " + sum + " (" + count + " readings)");
}
}How it works: the check comes before adding, so the failure value itself is never added. Readings after the failure (20 and 18) aren't trusted, so break, not continue.
First duplicate seat number
A booking list should have no repeated seat numbers. Find the first seat booked twice and the two positions where it appears.
seats = {14, 7, 22, 9, 7, 30}First duplicate: 7 (positions 2 and 5)
Show solution and explanation
public class Main {
public static void main(String[] args) {
int[] seats = {14, 7, 22, 9, 7, 30};
String result = "No duplicates";
outer:
for (int i = 0; i < seats.length; i++) {
for (int j = i + 1; j < seats.length; j++) {
if (seats[i] == seats[j]) {
result = "First duplicate: " + seats[i]
+ " (positions " + (i + 1) + " and " + (j + 1) + ")";
break outer;
}
}
}
System.out.println(result);
}
}How it works: compare every pair once: the inner loop starts at i + 1. When a match is found, break outer stops both loops. A plain break would only stop the inner loop and the search would carry on. (With a HashSet, Lesson 11.5, this takes one pass instead of two loops.)
Next prime after a number
Find the smallest prime number greater than n, using a labelled continue.
n = 100
Next prime after 100: 101
Show solution and explanation
public class Main {
public static void main(String[] args) {
int n = 100;
int answer = -1;
candidates:
for (int c = n + 1; ; c++) {
for (int d = 2; d * d <= c; d++) {
if (c % d == 0) {
continue candidates; // not prime: try the next candidate
}
}
answer = c; // no divisor found
break;
}
System.out.println("Next prime after " + n + ": " + answer);
}
}How it works: as soon as a divisor is found, continue candidates abandons this candidate and moves the outer loop on. If the inner loop finishes without finding a divisor, the candidate is prime, so we record it and break.
Read words until STOP
A list of words ends with the marker word STOP. Count the real words before it, ignoring blank entries.
words = {"chai", "", "samosa", " ", "vada", "STOP", "extra"}Words before STOP: 3
Show solution and explanation
public class Main {
public static void main(String[] args) {
String[] words = {"chai", "", "samosa", " ", "vada", "STOP", "extra"};
int count = 0;
for (String w : words) {
if (w.equals("STOP")) {
break;
}
if (w.isBlank()) {
continue;
}
count++;
}
System.out.println("Words before STOP: " + count);
}
}How it works: two rules in one loop: the sentinel STOP uses break, and blank entries use continue. isBlank() (Java 11+) is true for empty strings and strings of only spaces. Words are compared with equals, never == (Lesson 2.3).
Find the best block of cinema seats
A cinema has rows A–E. Each row is a string where X is booked and . is free. Find the front-most row with 3 free seats side by side and print their seat numbers (seats are numbered from 1).
A "XXXXXXXX" B "XX.X..XX" C "X...XXXX" D "........" E "........"
Best seats: C2-C4
Show solution and explanation
public class Main {
public static void main(String[] args) {
String[] rows = {"XXXXXXXX", "XX.X..XX", "X...XXXX", "........", "........"};
int need = 3;
String result = "No block of " + need + " seats available";
search:
for (int r = 0; r < rows.length; r++) {
int run = 0; // free seats in a row so far
for (int s = 0; s < rows[r].length(); s++) {
if (rows[r].charAt(s) == '.') {
run++;
if (run == need) {
char row = (char) ('A' + r);
int first = s - need + 2; // seat numbers start at 1
result = "Best seats: " + row + first + "-" + row + (s + 1);
break search;
}
} else {
run = 0; // a booked seat breaks the run
}
}
}
System.out.println(result);
}
}How it works:
- Rows are searched front to back, and seats left to right, so the first match is the best one.
runcounts consecutive free seats; a booked seat resets it. Row B has free seats 3, 5 and 6, but never 3 in a row.- When
runreaches 3, we convert indexes to what customers see: row letter'A' + rand seat numbers starting at 1. break searchstops both loops immediately. In real code this search would be a method thatreturns the block.
Daily payment batch with a safety stop
A payments batch processes transfers in order. Negative amounts are refunds handled by another system, so skip them. Any single transfer above ₹50,000 must stop the batch for manual review. Report what was processed, skipped and flagged.
transfers = {1500, -300, 2200, 64000, 900}Processed 2 transfers, total Rs 3700 Skipped refunds: 1 Batch stopped at #4 (Rs 64000) for review
Show solution and explanation
public class Main {
public static void main(String[] args) {
int[] transfers = {1500, -300, 2200, 64000, 900};
final int REVIEW_LIMIT = 50_000;
int processed = 0, total = 0, skipped = 0;
int stoppedAt = -1; // -1 means "finished normally"
for (int i = 0; i < transfers.length; i++) {
int amount = transfers[i];
if (amount < 0) {
skipped++;
continue; // refunds go elsewhere
}
if (amount > REVIEW_LIMIT) {
stoppedAt = i;
break; // stop everything
}
total += amount;
processed++;
}
System.out.println("Processed " + processed + " transfers, total Rs " + total);
System.out.println("Skipped refunds: " + skipped);
if (stoppedAt >= 0) {
System.out.println("Batch stopped at #" + (stoppedAt + 1)
+ " (Rs " + transfers[stoppedAt] + ") for review");
} else {
System.out.println("Batch completed");
}
}
}How it works:
- Two different rules: refunds are skipped (the batch continues), large transfers stop the batch (so nothing after them is processed out of order).
stoppedAtremembers why the loop ended. After the loop, break and normal completion look the same unless we record it.- Using a classic for loop gives us the index, so the report can say exactly which transfer stopped the batch.
- A real batch would also record each transfer's status in a database so it can resume from #4 after review.
Real-world scenario questions (asked in company interviews)
break and continue are simple, but they hide some classic production bugs. Decide your answer first, then open the model answer.
The tool ignores the quit command
A command-processing loop uses switch (cmd), and case "QUIT": break; is supposed to end processing. Instead, the remaining commands keep running after QUIT. Why?
The interviewer is checking: do you know that break applies to the innermost switch or loop?
Show a strong answer
The break inside the switch only exits the switch, which is the innermost breakable statement. The loop around it carries on with the next command.
- Use a labelled break: put
commands:on the loop and writebreak commands;. - Or set a flag (
running = false) checked by the loop, or move the loop into a method andreturn. - Add a test where QUIT is followed by other commands.
Avoid saying: “break always exits the loop.”
The import job froze on row 2
A CSV import uses int i = 0; while (i < rows.size()) { if (rows.get(i).isBlank()) continue; save(rows.get(i)); i++; }. It works on clean files but hangs forever on a file whose second row is blank. Explain.
The interviewer is checking: do you know continue in a while loop skips the update at the bottom?
Show a strong answer
In a while loop, continue jumps straight back to the condition. The i++ at the bottom is skipped, so i stays on the blank row forever and the loop never ends.
- Use a for loop, where continue still runs the update:
for (int i = 0; i < rows.size(); i++), or a for-each. - If it must be a while loop, increment before the continue.
- Add a test file with blank rows, and a job timeout in production.
Avoid: “Add a counter that breaks after 1,000,000 iterations” as the fix. It hides the real bug.
Checking “any unpaid order?” on 50,000 orders
A dashboard checks whether a seller has any unpaid order by looping through all 50,000 orders and setting hasUnpaid = true when one is found. It works but is slow. What would you change?
The interviewer is checking: do you use early exit, and do you think about where the work should happen?
Show a strong answer
- Add
breakas soon as the first unpaid order is found: the answer is already known. - Better, extract a method
hasUnpaidOrder(orders)that returns true at the first match (or usestream().anyMatch(…)later). - Best for real systems: ask the database (
SELECT 1 … WHERE status = 'UNPAID' LIMIT 1) instead of loading 50,000 orders into memory.
Avoid: looping through everything when only a yes/no answer is needed.
Three levels of labelled breaks
A pricing method has three nested loops (regions, stores, products) with labels and several break region; and continue store; statements. It's correct, but reviewers find it hard to follow. How would you refactor it?
The interviewer is checking: do you know when to replace labelled jumps with methods?
Show a strong answer
- Extract the inner loops into well-named methods, e.g.
findPriceInStore(store, product), and usereturnto leave early. Each method then has one simple loop. - Turn complex skip conditions into helper methods such as
isStoreActive(store). - Keep behaviour identical: write tests first, then refactor in small steps.
Avoid saying: “Labels are never allowed.” One labelled break in a small search is fine; deep chains are the problem.