JAVA • CONTROL FLOW

Break & Continue — Use break and continue appropriately

Master the two keywords that let you control exactly when and how your loops execute.

Historical Context & Motivation

When early programmers wrote code in the 1950s and 1960s, the primary way to control program flow was the GOTO statement — a command that told the computer to jump to a specific line number. While powerful, GOTO created tangled, hard-to-read programs that people began calling spaghetti code. As programming languages matured, designers looked for more structured ways to let programmers exit or skip parts of loops without resorting to arbitrary jumps.

1964
BASIC and GOTO
The BASIC language popularized the GOTO statement, which allowed programmers to jump to any line. Programs quickly became tangled and difficult to debug.
1968
Structured Programming Movement
Edsger Dijkstra published his famous letter "Go To Statement Considered Harmful," arguing that programs should rely on loops and conditionals rather than arbitrary jumps.
1972
C Language Introduces break and continue
Dennis Ritchie's C language introduced break and continue as structured alternatives to GOTO within loops, giving programmers precise control without sacrificing readability.
1995
Java Adopts break and continue
Java inherited break and continue from C but deliberately excluded GOTO. Java also added labeled versions of both keywords for use with nested loops.

The core question these keywords answer is simple: what happens when you need to stop a loop early or skip over certain iterations? Without break and continue, you would have to use complicated boolean flags and nested if-statements. These two keywords give you clean, readable control over your loop's behavior.

Core Principles & Definitions

Both break and continue are jump statements in Java — they alter the normal sequential flow of a loop. Understanding when to use each one is essential to writing efficient and readable code. Here are the foundational ideas you need to know.

1

break Exits the Loop

When Java encounters a break statement inside a loop, it immediately terminates the entire loop and resumes execution at the first statement after the loop body.
2

continue Skips to the Next Iteration

When Java encounters a continue statement, it skips the remaining code in the current iteration and jumps back to the loop's condition check (or update expression in a for loop).
3

Both Work Inside Loops Only

You can only use break and continue inside for, while, or do-while loops. Using break inside a switch statement exits the switch, not an enclosing loop.
4

Labeled Versions for Nested Loops

Java supports labeled break and labeled continue. A label lets you target a specific outer loop when you have loops inside loops, giving you finer control.
✦ KEY TAKEAWAY
Think of a loop like running laps around a track. break is like leaving the track entirely and heading to the parking lot — you're done running. continue is like skipping over a puddle on the track — you don't stop running, you just skip that part and keep going to the next lap.

Visual Explanation

How break and continue Alter Loop Flow

On the left, break terminates the entire loop and sends execution past the closing brace. On the right, continue skips the remaining statements in the current iteration and jumps back to the loop's condition check.

Notice the key difference in the diagram above. The break path leads downward and completely exits the loop structure. The continue path curves back up to the condition check, allowing the loop to proceed with the next iteration. In a for loop specifically, continue also triggers the update expression (like i++) before the condition is re-evaluated.

How break and continue Work Under the Hood

break in Detail

The break statement is most commonly used in two contexts: inside loops and inside switch statements. When used inside a loop, break causes immediate termination of the innermost enclosing loop. All remaining iterations are abandoned, and execution continues with the statement right after the loop's closing brace.

💻 Syntax: break
for (int i = 0; i < 10; i++) { if (i == 5) { break; // exits loop when i is 5 } System.out.println(i); } // Prints: 0, 1, 2, 3, 4

continue in Detail

The continue statement does not terminate the loop — it only skips the rest of the current iteration. In a for loop, after continue executes, the update expression runs (e.g., i++), and then the condition is checked again. In a while loop, execution jumps directly back to the condition, so you must make sure the loop variable is updated before the continue — otherwise you can create an infinite loop.

💻 Syntax: continue
for (int i = 0; i < 6; i++) { if (i == 3) { continue; // skips printing 3 } System.out.println(i); } // Prints: 0, 1, 2, 4, 5

Labeled break and continue

When you have nested loops (a loop inside a loop), a plain break only exits the innermost loop. If you want to break out of an outer loop, you can use a labeled break. You place a label (an identifier followed by a colon) before the outer loop, and then write break labelName; inside the inner loop.

🏷️ Syntax: Labeled break
outer: for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (i == 1 && j == 1) { break outer; // exits BOTH loops } System.out.println(i + "," + j); } } // Prints: 0,0 0,1 0,2 1,0

Behavior Across Different Loop Types

The behavior of break and continue varies slightly depending on the type of loop you are using. The diagram below illustrates what happens to the loop counter and condition check in each case.

This chart compares how break and continue behave in the four loop types Java provides. Pay special attention to the warning about while loops and continue — this is a frequent source of bugs.
Summary of break and continue behavior by loop type
Keywordfor loopwhile loopdo-while loop
breakExits loop, skips updateExits loop immediatelyExits loop, skips bottom condition
continueRuns update, then conditionJumps to condition (no auto-update!)Jumps to condition at bottom

Worked Example

Let's trace through a realistic scenario. Imagine you have an array of test scores and you want to find the first failing score (below 60). Once found, you stop searching. You also want to skip any score of exactly 0 because those represent students who didn't take the test.

Finding the First Failing Score
1
Step 1 — Set Up the DataWe declare an array of scores and a variable to store our result: int[] scores = {85, 92, 0, 73, 55, 0, 41, 88}; int firstFail = -1; // -1 means "not found yet"
2
Step 2 — Write the Loop with continueWe use a for-each loop to iterate through the scores. We use continue to skip scores of 0 (absent students): for (int score : scores) { if (score == 0) { continue; // skip absent students } // more logic below }
Scores of 0 at indices 2 and 5 will be skipped entirely.
3
Step 3 — Add the break ConditionAfter the continue check, we look for the first failing score. If found, we save it and break out of the loop: for (int score : scores) { if (score == 0) { continue; } if (score < 60) { firstFail = score; break; // found it, stop searching } }
4
Step 4 — Trace the ExecutionLet's walk through each iteration: • 85 → not 0, not < 60 → continue loop • 92 → not 0, not < 60 → continue loop • 0 → is 0 → continue (skip) • 73 → not 0, not < 60 → continue loop • 55 → not 0, IS < 60 → firstFail = 55 → break!
firstFail = 55. The loop never checks indices 5, 6, or 7.
5
Step 5 — Output the Resultif (firstFail == -1) { System.out.println("No failing scores found."); } else { System.out.println("First failing score: " + firstFail); }
Output: First failing score: 55

Best Practices & Common Mistakes

While break and continue are powerful tools, using them incorrectly can make your code confusing or buggy. Here is a comparison of good and bad usage patterns.

Good practices versus common mistakes
✅ Good Practice❌ Common Mistake
Use break for early termination when searching (e.g., finding the first match in an array).Using break in every iteration instead of adjusting the loop condition — this makes the loop condition meaningless.
Use continue to skip invalid or unwanted data while processing a collection.Using continue in a while loop without updating the counter first, causing an infinite loop.
Use labeled break sparingly to exit nested loops when a complex condition is met.Overusing labeled break/continue — this makes code harder to read. Consider extracting nested loops into a separate method instead.
Place break/continue near the top of the loop body (as a guard clause) so readers see the skip condition immediately.Burying break/continue deep inside complex nested if-statements where they are hard to spot.
✦ KEY TAKEAWAY
Think of break and continue like exception tools, not default tools. A well-designed loop often doesn't need them at all. Use them when they make your intent clearer, not as a substitute for thinking through your loop condition.
⚠️ Infinite Loop Warning
This code creates an infinite loop because continue skips the update of i: int i = 0; while (i < 10) { if (i == 5) { continue; // BUG: i is never incremented past 5! } System.out.println(i); i++; } Fix: move i++ before the continue, or use a for loop instead.

Connection to Advanced Concepts

As you advance in Java, you'll encounter situations where the ideas behind break and continue show up in more sophisticated forms. Understanding them now builds a foundation for more powerful techniques.

How break and continue concepts evolve in advanced Java
Concept NowAdvanced VersionWhere You'll See It
break in loopsreturn in methodsWhen a loop is inside a method, returning early achieves the same effect as break and also sends a value back to the caller.
continue to skip itemsStream API filter()Java Streams let you filter out unwanted elements declaratively, replacing manual continue-based loops.
Labeled breakExceptions and try-catchFor deeply nested code, throwing and catching exceptions provides structured exits, though this should only be used for error handling.
break in switchSwitch expressions (Java 14+)Modern switch expressions use arrow syntax and don't need break at all — fall-through is eliminated by design.

As you learn about methods and return statements in the next unit, you'll see that extracting a loop into its own method lets you use return instead of break, which is often cleaner. Later, when you study the Java Streams API, you'll find that operations like filter(), findFirst(), and anyMatch() provide elegant alternatives to manual loops with break and continue.

Practice Problems

PROBLEM 1 — CONCEPTUAL
What is the fundamental difference between break and continue? If a loop contains a break statement inside an if block, does the loop always terminate early?
PROBLEM 2 — BASIC CALCULATION
What does the following code print? for (int i = 1; i <= 8; i++) { if (i % 2 == 0) { continue; } System.out.print(i + " "); }
PROBLEM 3 — INTERMEDIATE
Consider the following code with nested loops. What is printed, and why? for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (j == 1) { break; } System.out.print("(" + i + "," + j + ") "); } }
PROBLEM 4 — APPLIED
You are writing a program to read user input until they type "quit". For each input, skip blank lines (empty strings) and process only non-blank input. Write a loop using both break and continue that accomplishes this. Assume you have a Scanner object called scanner.
PROBLEM 5 — CRITICAL THINKING
A classmate argues that break and continue should never be used because you can always rewrite a loop without them using boolean flags and extra if-statements. Write a short code example that uses break and then rewrite it without break. Which version is more readable? Are there situations where avoiding break/continue is actually better?

Lesson Summary

Java's break statement immediately terminates the entire loop and transfers control to the first statement after the loop. The continue statement skips the remaining code in the current iteration and proceeds to the next cycle of the loop. In a for loop, continue triggers the update expression before re-checking the condition, while in a while loop, it jumps directly to the condition — so you must update your counter before the continue to avoid an infinite loop.

For nested loops, Java provides labeled break and labeled continue to target a specific outer loop. Use break for early termination (like finding the first match in a search) and continue for skipping unwanted data (like filtering out invalid inputs). Both keywords should be used to make code clearer, not as a substitute for well-designed loop conditions.

Varsity Tutors • Java • Break & Continue — Use break and continue appropriately