break, continue and labelled loops

Sometimes a loop shouldn't run to the end. Found what you were looking for? Stop. Hit a bad record? Skip it and carry on. Java's break and continue do exactly this, and labels let them work across nested loops. You'll see exactly where each one jumps to, and the classic bugs they cause when used carelessly.

Module 3 · Control Flow⏱ 17 minBeginner8 practice problems
1 The story

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.

120 −5 340 0 9,99,999 85 addcontinue (skip)addcontinue (skip)break (stop!)never visited exit loop → total = 460 myphatshala.in
Riya

Sir, can I skip just the bad entries but still finish the list? And separately, stop everything when something looks like fraud?

Arjun Sir

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.

Riya

And if the loop is inside another loop?

Arjun Sir

Then you can put a label on the outer loop and say exactly which loop to break out of. Let's see all three.

2 Definition

What are break and continue?

Formal definition (write this in exams)

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.

In simple words

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

Early exitLeaving a loop as soon as the answer is known, using break.
SkipIgnoring one item and moving on, using continue.
LabelA name followed by a colon in front of a loop: search: for (…).
Nested loopA loop inside another loop (Lesson 3.6).
returnLeaves the whole method, not just the loop.
FlagA boolean that records why a loop ended, e.g. found.

Where each one jumps

StatementJumps toTypical use
break;The first statement after the innermost loop or switchFound it; stop searching
continue; in forThe update part (i++), then the conditionSkip invalid items
continue; in while / do-whileThe conditionSkip, but beware of skipping your own update
break label;After the labelled loopLeave nested loops at once
continue label;The next iteration of the labelled loopGive up on this outer item
return;Out of the whole methodThe 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”).

3 Types and ways to use it

The four jumps, with typical uses

break

Linear search, stopping at the first match, or stopping when a limit is hit.

Stop early

continue

Skip blank lines in a file, refunds in a sales total, or inactive users in a mailing.

Skip one

labelled break

Searching a grid (seats, a chessboard, a matrix) and stopping both loops at the first hit.

Nested loops

labelled continue

“This candidate failed one check; move on to the next candidate” from inside an inner loop.

Nested loops

Alternatives that are often clearer

Instead ofConsider
Labelled break out of deep nestingMove the loops into a method and use return
Many continue statements in one loopOne 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)
4 Step by step

Adding skip and stop rules to a loop

  1. Start with the plain loop

    for (int amount : orders) {
        total += amount;
    }
    Without extra rules, every element is visited and added, including the bad ones.
  2. Skip invalid items with continue, near the top

    if (amount <= 0) {
        continue;
    }
    continue compiles to a goto that jumps to the loop's “next element” step, skipping the rest of the body.
  3. Stop on a serious problem with break

    if (amount > 50_000) {
        break;
    }
    break is a goto to the first instruction after the loop. The remaining elements are never visited.
  4. 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.
  5. Use a label only for nested loops

    search:
    for (int r = 0; r < rows; r++) {
        for (int s = 0; s < seats; s++) {
            if (free(r, s)) { break search; }
        }
    }
    A label is not a goto target you can jump to from anywhere. It can only name an enclosing loop, and break search jumps just past that loop.
5 See it happen

Skip, skip, stop: both views

Left: the order list being processed. Right: the stack and the jumps in the bytecode.

Processing {120, −5, 340, 0, 999999, 85} 6 steps
What you see 120 −5 340 0 999999 85 +120 → total 120 Skipping invalid amount -5 +340 → total 460 Skipping invalid amount 0 Suspicious amount 999999: stopping Total processed: Rs 460 Valid: added to the total. Invalid: continue skips the rest of this round. Valid: added. total = 460. 0 is invalid too: continue again. Over the limit: break leaves the loop now. 85 was never even looked at. myphatshala.in
Behind the screen NEXT: i < length? else → END amount = orders[i] if (amount <= 0): println · goto STEP if (amount > 50000): println · goto END total += amount STEP: i++ · goto NEXT END: println(total) frame i 01234 total 120460 Normal path: falls through to total += amount. continue = goto STEP: the i++ part still runs. Normal path again. Same jump to STEP. break = goto END: past the loop entirely. i stopped at 4; index 5 was never read. myphatshala.in
6 Real-world use

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.

continue on booked, break on found 6 steps
Animated example if (booked[s]) continue; if (window[s]) break; 1 window booked 2 middle 3 aisle booked 4 window 5 middle 6 window s seat 1 booked → continue (skip) seat 2 free, but middle → keep looking seat 3 booked → continue seat 4 free and window → break! seats 5 and 6 are never checked Allotted seat 4 (window) myphatshala.in

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.

Scan slots→first free → break→Show slot

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.

Row 57 invalid→log + continue→Rows 58… imported

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.

Rows × seats→break search→C2–C4 offered
!

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 failures in a row→break + alert→Resume later
skip unsubscribedcontinue

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.

All users→if unsubscribed: continue→Only consenting users

Examples are simplified. Real systems log every skipped or failed item.

7 Run the code

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);
    }
}
Skipping invalid amount -5 Skipping invalid amount 0 Suspicious amount 999999: stopping Total processed: Rs 460
  • continue;Skips total += amount for 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.
8 Line by line

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.

Example 1Inventory · stock

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.

Input
items Rice, Oil, Sugar, Salt, Tea, Dal; stock 40, 12, 0, 25, 0, 8
Expected output
First out of stock: Sugar (checked 3 items)

Approach

  1. Loop over the items.
  2. When stock is 0, remember the item and break.
  3. 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.

Example 2E-commerce · orders

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.

Input
amounts 450, 1200, 300, 800; statuses OK, CANCELLED, OK, OK
Expected output
Revenue: Rs 1550

Approach

  1. Loop over the orders.
  2. If cancelled, continue: go straight to the next order.
  3. 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.

Example 3Cinema · seats

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.

Input
rows {1,1,1,1}, {1,1,0,1}, {0,0,0,0}
Expected output
First free seat: B3

Approach

  1. Label the outer loop search:.
  2. When a free seat is found, record it and break search;.
  3. 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.

9 Quiz and revision

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 goto jumps. Prefer return from 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.

P1Easy

First number divisible by 7 and 11

Find the first number greater than 500 that's divisible by both 7 and 11.

Input
start = 500
Expected output
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);
    }
}
First match after 500: 539

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.

P2Easy

Skip the multiples of 3

Print the numbers from 1 to 20, skipping multiples of 3.

Input
limit = 20
Expected output
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);
    }
}
1 2 4 5 7 8 10 11 13 14 16 17 19 20

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.

P3Easy

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).

Input
readings = {12, 15, 9, -1, 20, 18}
Expected output
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)");
    }
}
Sum before failure: 36 (3 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.

P4Medium

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.

Input
seats = {14, 7, 22, 9, 7, 30}
Expected output
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);
    }
}
First duplicate: 7 (positions 2 and 5)

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.)

P5Medium

Next prime after a number

Find the smallest prime number greater than n, using a labelled continue.

Input
n = 100
Expected output
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);
    }
}
Next prime after 100: 101

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.

P6Medium

Read words until STOP

A list of words ends with the marker word STOP. Count the real words before it, ignoring blank entries.

Input
words = {"chai", "", "samosa", "  ", "vada", "STOP", "extra"}
Expected output
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);
    }
}
Words before STOP: 3

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).

P7Business problem

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).

Input
A "XXXXXXXX"
B "XX.X..XX"
C "X...XXXX"
D "........"
E "........"
Expected output
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);
    }
}
Best seats: C2-C4

How it works:

  1. Rows are searched front to back, and seats left to right, so the first match is the best one.
  2. run counts consecutive free seats; a booked seat resets it. Row B has free seats 3, 5 and 6, but never 3 in a row.
  3. When run reaches 3, we convert indexes to what customers see: row letter 'A' + r and seat numbers starting at 1.
  4. break search stops both loops immediately. In real code this search would be a method that returns the block.
P8Business problem

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.

Input
transfers = {1500, -300, 2200, 64000, 900}
Expected output
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");
        }
    }
}
Processed 2 transfers, total Rs 3700 Skipped refunds: 1 Batch stopped at #4 (Rs 64000) for review

How it works:

  1. Two different rules: refunds are skipped (the batch continues), large transfers stop the batch (so nothing after them is processed out of order).
  2. stoppedAt remembers why the loop ended. After the loop, break and normal completion look the same unless we record it.
  3. Using a classic for loop gives us the index, so the report can say exactly which transfer stopped the batch.
  4. 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.

Internal tool · bug reportFresher

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 write break commands;.
  • Or set a flag (running = false) checked by the loop, or move the loop into a method and return.
  • Add a test where QUIT is followed by other commands.

Avoid saying: “break always exits the loop.”

Data pipeline · hung jobFresher

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.

E-commerce · performanceFresher

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 break as 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 use stream().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.

Any company · code review1–3 years

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 use return to 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.