Java Notes
Complete guide to break and continue statements in Java covering labeled/unlabeled break, continue in loops, break in switch, use cases, flow diagrams, and best practices with detailed examples.
Introduction to Jump Statements
Java provides three jump statements (also called transfer statements) that transfer control to another part of the program:
- break — exits the current loop or switch immediately
- continue — skips the rest of the current iteration and moves to the next
- return — exits the current method (covered in methods chapter)
These statements give you fine-grained control over loop execution, allowing you to handle special conditions without complex boolean flags.
The break Statement
What Does break Do?
The break statement immediately terminates the innermost enclosing loop or switch statement. Execution continues with the statement immediately following the terminated structure.
Flow Diagram
break in for Loop
Searching for 35 in the array... Checking index 0: 10 Checking index 1: 20 Checking index 2: 35 Found 35 at index 2! Breaking... Loop ended.
Explanation: The loop checked indices 0, 1, and 2. When it found 35 at index 2, break terminated the loop. Indices 3 and 4 were never checked.
break in while Loop
Sum exceeded 20! Breaking at number = 6 Final sum: 21 Last number added: 6
Explanation: Using while(true) with break is a common pattern when the exit condition is complex or checked in the middle of the loop body (not just at the top).
break in switch Statement
Wednesday Without break (fall-through): Wednesday Thursday Other day
Explanation: Without break, execution "falls through" from the matching case to all subsequent cases, executing their code regardless of whether the case value matches.
break in do-while Loop
i = 1 i = 2 i = 3 i = 4 Breaking at i = 5 After loop: i = 5
Labeled break
A labeled break terminates an outer loop, not just the innermost one. This is essential when working with nested loops.
Syntax
labelName:
for (...) {
for (...) {
if (condition) {
break labelName; // Exits the OUTER loop
}
}
}Example: Search in 2D Array
Checking [0][0] = 1 Checking [0][1] = 2 Checking [0][2] = 3 Checking [1][0] = 4 Checking [1][1] = 5 Found 5 at [1][1]
Without labeled break, a regular break would only exit the inner loop, and the outer loop would continue with the next row.
The continue Statement
What Does continue Do?
The continue statement skips the rest of the current iteration and jumps to the next iteration of the loop. Unlike break, it does NOT exit the loop — it just skips ahead.
Flow Diagram
| Yes | |
|---|---|
| ▼ | |
| Execute statements (after) |
continue in for Loop
Printing odd numbers from 1 to 10: 1 3 5 7 9
Explanation: When i is even (2, 4, 6, 8, 10), continue skips the println and jumps directly to i++. The loop continues normally for odd numbers.
continue in while Loop — CAUTION!
Skipping multiples of 3: 1 2 4 5 7 8 10
CRITICAL WARNING: If you put i++ AFTER continue, you create an infinite loop because continue skips the increment!
continue vs for loop increment
In a for loop, continue always executes the increment expression (i++), so infinite loops don't happen:
Labeled continue
A labeled continue skips to the next iteration of an outer loop.
Printing pairs where j > i: (1, 2)
Explanation: For each i, as soon as j <= i is true (which happens at j=1 for i>=1, except i=1 where j starts equal), it skips to the next i. Actually for i=1, j=1 → j<=i is true, so continue outer happens immediately for i=1 too... Let me fix the logic:
Skipping row when product > 10: 1 2 3 4 2 4 6 8 3 6 9 (skipping rest of row 3) 4 8 (skipping rest of row 4)
break vs continue — Comparison
| Feature | break | continue |
|---|---|---|
| Effect | Terminates the entire loop | Skips current iteration only |
| Loop continues? | No — exits immediately | Yes — next iteration starts |
| Where to use | Exit when target found | Skip unwanted elements |
| In switch | Prevents fall-through | Not applicable |
| Labeled version | Exits outer loop | Skips outer loop iteration |
| After statement | Code after loop executes | Code before continue still ran |
Side-by-Side Example
public class BreakVsContinue {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// Using break: stop at first number > 5
System.out.print("break (stop at >5): ");
for (int num : numbers) {
if (num > 5) break;
System.out.print(num + " ");
}
System.out.println();
// Using continue: skip numbers > 5
System.out.print("continue (skip >5): ");
for (int num : numbers) {
if (num > 5) continue;
System.out.print(num + " ");
}
System.out.println();
}
}break (stop at >5): 1 2 3 4 5 continue (skip >5): 1 2 3 4 5
Wait — both give the same output here because the array is sorted. Let me use an unsorted array:
public class BreakVsContinue2 {
public static void main(String[] args) {
int[] numbers = {3, 7, 1, 8, 2, 9, 4, 6};
System.out.print("break (stop at >5): ");
for (int num : numbers) {
if (num > 5) break;
System.out.print(num + " ");
}
System.out.println();
System.out.print("continue (skip >5): ");
for (int num : numbers) {
if (num > 5) continue;
System.out.print(num + " ");
}
System.out.println();
}
}break (stop at >5): 3 continue (skip >5): 3 1 2 4
Now the difference is clear: break stops at the first element > 5 (exits the loop). continue skips elements > 5 but keeps processing the rest.
Practical Use Cases
Use Case 1: Input Validation Loop
import java.util.Scanner;
public class InputValidation {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int age;
while (true) {
System.out.print("Enter age (1-120): ");
age = sc.nextInt();
if (age >= 1 && age <= 120) {
break; // Valid input — exit loop
}
System.out.println("Invalid! Try again.");
}
System.out.println("Your age: " + age);
sc.close();
}
}Enter age (1-120): -5 Invalid! Try again. Enter age (1-120): 200 Invalid! Try again. Enter age (1-120): 25 Your age: 25
Use Case 2: Processing Data with Skip Conditions
Valid emails: 1. alice@gmail.com 2. bob@yahoo.com 3. charlie@outlook.com 4. dave@gmail.com Total valid: 4
Use Case 3: First Prime Number Greater Than N
First prime after 20 is: 23
Common Mistakes
1. Infinite Loop with continue in while
2. Break Only Exits Innermost Loop
3. Unreachable Code After break/continue
4. Using break Instead of continue (Logic Error)
// WRONG: Stops processing entirely when finding invalid data
for (String item : data) {
if (!isValid(item)) break; // Should be continue!
}
// RIGHT: Skip invalid items and process the rest
for (String item : data) {
if (!isValid(item)) continue;
process(item);
}5. Overusing break/continue (Spaghetti Code)
// BAD: Multiple breaks make logic hard to follow
// BETTER: Restructure with clear conditions
// Instead of multiple continue checks, use a single if with &&Best Practices
- Use break for early termination when you've found what you're looking for
- Use continue to skip invalid data rather than deeply nesting if-else
- Prefer for loops with continue over while loops (avoid infinite loop bug)
- Use labeled break sparingly — consider extracting to a method with return instead
- Don't use break to exit infinite loops if a proper condition would work
- Keep loop bodies simple — if you need many breaks/continues, refactor
- Comment WHY you're breaking — the condition is the what, explain the why
- Avoid break in switch without clear intent — document intentional fall-through
- Test edge cases — what if break/continue triggers on first or last iteration?
- Consider alternatives — Streams with filter() can replace continue patterns
Interview Questions
Q1: What is the difference between break and continue? break terminates the entire loop; continue skips only the current iteration and moves to the next one.
Q2: Can break be used outside a loop or switch? No. Using break outside a loop/switch causes a compile error.
Q3: What is a labeled break? A break that specifies which enclosing loop to terminate, using a label. It's used to exit outer loops from within nested loops.
Q4: What happens to the loop variable after break? It retains its last value. After break, the variable is accessible if it was declared outside the loop.
Q5: Can you have multiple break statements in a loop? Yes, but only one will execute per iteration. Multiple breaks are often in different if-conditions.
Q6: What is the continue behavior difference between for and while loops? In for, continue skips to the increment step (i++). In while, continue skips to the condition check — the increment must be placed before continue or you risk infinite loops.
Q7: Is break in switch the same as break in loops? The keyword is the same, but semantics differ. In switch, it prevents fall-through. In loops, it exits the loop.
Q8: Can you break out of an if statement? No. break only works with loops and switch. You cannot break out of an if-else.
Q9: What is the alternative to labeled break? Extract the nested loop logic into a separate method and use return instead of labeled break.
Q10: Does continue affect the loop condition in a for loop? No. After continue, the increment expression runs, then the condition is checked normally.
Q11: What happens if break is inside a try-finally? The finally block executes before the break takes effect.
Q12: Can you use break with enhanced for (for-each) loops? Yes. break works the same way in for-each loops as in regular for loops.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for break and continue in Java.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, fundamentals, control, statements
Related Java Master Course Topics