Java for Beginners · Module 4: Control Flow
🎯 Changing the Flow Inside a Loop
Normally a loop runs until its condition fails. But sometimes you want to stop early (you found what you needed) or skip one pass (that value should be ignored). Java gives you two jump statements for this: break and continue.
| Statement | What it does | Typical use |
break | leaves the loop (or switch) right now | stop when the answer is found |
continue | skips the rest of this pass and starts the next | ignore unwanted values |
break label | leaves the loop that carries the label | exit nested loops at once |
continue label | jumps to the next pass of the labelled loop | skip a whole row |
Figure 1: Jump statements inside loops.
1️⃣ break
| i | i == 5 ? | Action | Printed so far |
| 1 | no | 1 | |
| 2 | no | 1 2 | |
| 3 | no | 1 2 3 | |
| 4 | no | 1 2 3 4 | |
| 5 | yes | break: loop ends | 1 2 3 4 |
Figure 2: Tracing break: the loop ends when i reaches 5.
Program 1: Stopping early
public class BreakDemo {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break;
}
System.out.print(i + " ");
}
System.out.println();
System.out.println("Loop stopped early");
int[] marks = {72, 55, 0, 81};
int found = -1;
for (int i = 0; i < marks.length; i++) {
if (marks[i] == 0) {
found = i;
break;
}
}
System.out.println("First zero at index " + found);
}
}
1 2 3 4
Loop stopped early
First zero at index 2
- When
ireaches 5,breakends the loop immediately. The numbers 5 to 10 are never printed. - The second loop is a search: as soon as the zero is found, there is no reason to check the rest.
breaksaves the work. - Starting
foundat -1 is a common way to say “not found yet”. Arrays andmarks.lengthare explained in Lesson 21. breakalso ends aswitchcase (Lesson 17).
2️⃣ continue
| i | i % 2 == 0 ? | Action |
| 1 | no | print 1 |
| 2 | yes | continue: skip print |
| 3 | no | print 3 |
| 4 | yes | continue: skip print |
| 5 | no | print 5 |
Figure 3: Tracing continue: even numbers are skipped, the loop goes on.
Program 2: Skipping some passes
public class ContinueDemo {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue;
}
System.out.print(i + " ");
}
System.out.println();
int sum = 0;
int[] data = {5, -3, 8, -1, 4};
for (int d : data) {
if (d < 0) {
continue;
}
sum += d;
}
System.out.println("Sum of positives = " + sum);
}
}
1 3 5 7 9
Sum of positives = 17
- For even numbers,
continueskips theprintand jumps to the nexti. The loop itself does not end. - In a
forloop,continuestill runs the update (i++). In awhileloop you must make sure the update is done before thecontinue, or the loop may never end. - The second loop adds only the positive numbers: 5 + 8 + 4 = 17.
3️⃣ Labelled break and continue
A plain break or continue affects only the innermost loop. To reach an outer loop, give it a label, which is a name followed by a colon, and use that name after break or continue.
label: outer
plain break leaves only this loop
break outer; jumps out of both loops. continue outer; jumps to the next pass of the outer loop.Figure 4: A label lets break and continue reach an outer loop.
public class LabelDemo {
public static void main(String[] args) {
System.out.println("Plain break (inner only):");
for (int r = 1; r <= 3; r++) {
for (int c = 1; c <= 3; c++) {
if (c == 2) break;
System.out.println("r=" + r + " c=" + c);
}
}
System.out.println("Labelled break (leaves both loops):");
outer:
for (int r = 1; r <= 3; r++) {
for (int c = 1; c <= 3; c++) {
if (r == 2 && c == 2) break outer;
System.out.println("r=" + r + " c=" + c);
}
}
System.out.println("Labelled continue:");
rows:
for (int r = 1; r <= 3; r++) {
for (int c = 1; c <= 3; c++) {
if (c == 2) continue rows;
System.out.println("r=" + r + " c=" + c);
}
}
}
}
Plain break (inner only):
r=1 c=1
r=2 c=1
r=3 c=1
Labelled break (leaves both loops):
r=1 c=1
r=1 c=2
r=1 c=3
r=2 c=1
Labelled continue:
r=1 c=1
r=2 c=1
r=3 c=1
- Plain break: each time c reaches 2, only the inner loop ends. The outer loop carries on to the next r.
- break outer: when r = 2 and c = 2, both loops end at once. Row 3 is never visited.
- continue rows: when c = 2, the program jumps to the next r, skipping the rest of the inner loop.
- Labels are rare in everyday code. Use them only when exiting nested loops is truly needed.
4️⃣ Useful Patterns
Program 4: Prime test with break
public class Prime {
public static void main(String[] args) {
int[] tests = {17, 20, 29, 1};
for (int n : tests) {
boolean prime = n > 1;
for (int d = 2; d * d <= n; d++) {
if (n % d == 0) {
prime = false;
break;
}
}
System.out.println(n + (prime ? " is prime" : " is not prime"));
}
}
}
17 is prime
20 is not prime
29 is prime
1 is not prime
- A number is not prime as soon as one divisor is found, so the inner loop can
breakat once. - Checking only up to the square root (
d * d <= n) is enough, since any larger divisor would pair with a smaller one.
Program 5: An intentional infinite loop that ends with break
import java.util.Scanner;
public class Guess {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int secret = 7;
while (true) {
System.out.print("Guess: ");
int g = sc.nextInt();
if (g == secret) {
System.out.println("Correct!");
break;
}
System.out.println(g < secret ? "Too low" : "Too high");
}
}
}
Guess: 3
Too low
Guess: 9
Too high
Guess: 7
Correct!
while (true)never ends by itself. The only exit is thebreakwhen the guess is right.- This is a common way to write “repeat until the user succeeds”.
5️⃣ Errors Beginners Meet
break outside a loop or switch
public class Bad1 {
public static void main(String[] args) {
int x = 5;
if (x > 3) {
break;
}
}
}
Bad1.java:5: error: break outside switch or loop
break;
^
1 error
breakneeds a loop or switch around it. Anifalone is not enough.
A label that does not exist
public class Bad2 {
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {
System.out.println(i);
continue outer;
}
}
}
Bad2.java:5: error: undefined label: outer
continue outer;
^
1 error
- The label must be written just before the loop it names, as in
outer: for (...).
⚠️ Common Mistakes
| Mistake | Problem | Fix |
|---|---|---|
Expecting break to leave both nested loops | Only the inner loop ends | Use a label, or a flag |
continue in a while loop before the update | Infinite loop | Update the counter first |
Code after break in the same block | Unreachable: compile error | Remove it |
Using break to avoid thinking about the condition | Confusing loops | Prefer a clear condition when possible |
Confusing break and continue | Whole loop ends versus one pass skipped | Trace one example by hand |
❓ Frequently Asked Questions
Q1. Is there a goto in Java?goto is a reserved word but it is not used. Labelled break and continue cover the legitimate cases.
Q2. What is the difference between break and return?break leaves only the loop. return leaves the whole method (Lesson 25).
Q3. Can I use continue inside a switch?
Yes, if the switch is inside a loop. It moves to the next pass of that loop.
Q4. Do labels have to be in capitals?
No. It is only a convention to make them stand out.
✅ Key Takeaways
breakends the loop (or switch) immediately.continueskips to the next pass of the loop.- Both affect only the innermost loop, unless you add a label.
while (true)with abreakis a valid “repeat until” pattern.- Use break for searches and early exits, and continue to skip unwanted values.
🔁 Module 4 Recap
Lessons 16 to 20 gave you every control-flow tool: if, switch, while, do-while, for, break and continue. In Module 5 you will start storing collections of data with arrays and strings.
🎓 Practice questions: (1) Read numbers until the user enters 0, then print their sum. (2) Print the numbers 1 to 20 but skip multiples of 3. (3) Search an array for a value and print its index, or “not found”. (4) What is the output of a nested loop where the inner loop contains break at c == 2? (5) Rewrite the guessing game so it stops after 3 wrong guesses.
All 30 lessons in this series (open course page)
Module 1 · Getting Started
- Lesson 1: What is Java? Features and Uses
- Lesson 2: Installing the JDK and Running Your First Program
- Lesson 3: JDK, JRE, JVM and WORA Explained
- Lesson 4: JVM Architecture and JIT Compilation
- Lesson 5: Hello World Program Explained Line by Line
Module 2 · Building Blocks
- Lesson 6: Comments, Identifiers and Keywords
- Lesson 7: Variables and Literals
- Lesson 8: Primitive Data Types in Java
- Lesson 9: Type Conversion and Casting
- Lesson 10: Taking Input with the Scanner Class
- Lesson 11: Escape Characters and Variable Scope in Java
Module 3 · Operators
- Lesson 12: Arithmetic Operators and Increment/Decrement in Java
- Lesson 13: Relational and Logical Operators in Java
- Lesson 14: Bitwise and Shift Operators in Java
- Lesson 15: Assignment, Ternary Operator and Operator Precedence in Java
Module 4 · Control Flow
- Lesson 16: if, if-else and else-if Ladder in Java
- Lesson 17: switch Statement in Java (Classic and Modern)
- Lesson 18: while and do-while Loops in Java
- Lesson 19: for Loop and Nested Loops (Patterns) in Java
- Lesson 20: break, continue and Labelled Loops in Java
Module 5 · Data and Methods
- Lesson 21: Arrays in Java (One-Dimensional)
- Lesson 22: Multidimensional Arrays in Java
- Lesson 23: Strings and the String Pool in Java
- Lesson 24: String Methods and StringBuilder in Java
- Lesson 25: Methods and Method Overloading in Java
- Lesson 26: Recursion Basics in Java
- Lesson 27: ArrayList and Wrapper Classes in Java
- Lesson 28: Exception Handling Basics in Java