Break, Continue, and Loop Control
Control loops with `break` and `continue` to stop a search early, skip invalid values and leave a controlled infinite loop.
আপনি একটি free preview lesson দেখছেন।
Lesson Overview
A loop normally continues until its condition becomes false. Sometimes that is too rigid: a search should stop as soon as the target is found, an invalid value should be skipped without stopping everything, and a menu loop should end the moment the user chooses Exit.
In Java, two statements change the normal flow of a loop: break and continue. Used well, they make loops shorter and clearer; used carelessly, they create infinite loops and control flow that is hard to follow. This lesson covers both sides.
Learning Objectives
After completing this lesson, you will be able to:
- Terminate a loop early using
break - Skip the current iteration using
continue - Stop a search loop when a result is found
- Skip invalid values
- Exit a controlled infinite loop
- Understand how
breakandcontinuebehave in nested loops - Identify common loop-control mistakes
What Is Loop Control?
A loop-control statement changes the normal execution flow of a loop. A normal for loop from 1 to 5 prints all five numbers. Using break, the loop can end early:
for (int number = 1; number <= 5; number++) {
if (number == 3) {
break;
}
System.out.println(number);
}
Output:
1
2
Using continue, only one iteration is skipped:
for (int number = 1; number <= 5; number++) {
if (number == 3) {
continue;
}
System.out.println(number);
}
Output:
1
2
4
5
break
break; immediately terminates the nearest loop. It does not terminate the entire program: execution continues with the first statement after the loop:
for (int number = 1; number <= 5; number++) {
if (number == 3) {
break;
}
System.out.println(number);
}
System.out.println("Loop finished");
Output:
1
2
Loop finished
The Position of break Matters
In the examples so far, break comes before printing, so 3 is never printed. With break after printing:
for (int number = 1; number <= 5; number++) {
System.out.println(number);
if (number == 3) {
break;
}
}
Output:
1
2
3
Statement order changes the result.
break in a Search Loop
Suppose we need to find the index of the first 'F' character in a String:
String text = "Java Foundation";
char target = 'F';
int foundIndex = -1;
for (int index = 0; index < text.length(); index++) {
if (text.charAt(index) == target) {
foundIndex = index;
break;
}
}
System.out.println("Found index: " + foundIndex);
Output:
Found index: 5
Once the target is found, there is no need to check the remaining characters. Therefore, break is very useful in search loops.
Checking Whether a Target Was Found
String text = "Learn Java";
char target = 'J';
boolean found = false;
for (int index = 0; index < text.length(); index++) {
if (text.charAt(index) == target) {
found = true;
break;
}
}
System.out.println("Found: " + found);
Output:
Found: true
Using break in an Infinite Loop
Here is an intentional infinite loop:
int number = 1;
while (true) {
System.out.println(number);
if (number == 5) {
break;
}
number++;
}
Output:
1
2
3
4
5
while (true) does not terminate on its own. Here, break acts as the exit condition.
Sentinel and break
Suppose -1 is the signal to end an input sequence:
int total = 0;
while (true) {
System.out.print("Enter a number or -1 to stop: ");
int number = Integer.parseInt(scanner.nextLine().strip());
if (number == -1) {
break;
}
total += number;
}
The if (number == -1) check with its break appears before processing. Therefore, the sentinel is not added to the total.
continue
continue does not terminate the entire loop. It skips the remaining statements in the current iteration and moves to the next iteration, as the second example in What Is Loop Control? showed: the iteration for 3 is skipped, and the loop goes on with 4 and 5.
How Does continue Work?
In a for loop:
for (initialization; condition; update) {
if (skipCondition) {
continue;
}
// Remaining statements
}
When continue executes:
- The remaining body of the current iteration is skipped
- The update expression executes
- The condition is checked again
- The next iteration begins
Even Numbers with continue
for (int number = 1; number <= 10; number++) {
if (number % 2 != 0) {
continue;
}
System.out.println(number);
}
Output:
2
4
6
8
10
The odd numbers are skipped.
Skipping Invalid Values
int total = 0;
for (int number = -3; number <= 5; number++) {
if (number < 0) {
continue;
}
total += number;
}
System.out.println(total);
Processed values:
0
1
2
3
4
5
Output:
15
Using continue as a Guard
Suppose you want to process only even numbers. Nested style:
for (int number = 1; number <= 10; number++) {
if (number % 2 == 0) {
int square = number * number;
System.out.println(number + " -> " + square);
}
}
Using continue:
for (int number = 1; number <= 10; number++) {
if (number % 2 != 0) {
continue;
}
int square = number * number;
System.out.println(number + " -> " + square);
}
Output:
2 -> 4
4 -> 16
6 -> 36
8 -> 64
10 -> 100
Skipping invalid or irrelevant cases early can often make the main logic flatter and easier to read.
continue in a while Loop
When using continue in a while loop, the counter update must be handled carefully. Correct:
int number = 0;
while (number < 5) {
number++;
if (number == 3) {
continue;
}
System.out.println(number);
}
Output:
1
2
4
5
The counter is updated before continue.
Infinite Loop Caused by continue
Wrong:
int number = 1;
while (number <= 5) {
if (number == 3) {
continue;
}
System.out.println(number);
number++;
}
When number is 3, continue executes, so number++; is skipped. number remains 3, and the loop continues indefinitely.
Safer while Structure
The correct example above updates number at the start of the body, before continue can run. Updating first avoids this particular problem.
break vs. continue
| Statement | Effect |
|---|---|
break | Terminates the nearest loop |
continue | Skips only the current iteration |
The examples in "What Is Loop Control?" show both side by side: with break the output is 1 2, and with continue it is 1 2 4 5.
Nested Loops
Nested Loops and break
A normal break terminates only the nearest loop:
for (int row = 1; row <= 3; row++) {
for (int column = 1; column <= 3; column++) {
if (column == 2) {
break;
}
System.out.println(row + ", " + column);
}
}
Output:
1, 1
2, 1
3, 1
The inner loop ends at column == 2 for each row. The outer loop continues.
Nested Loops and continue
for (int row = 1; row <= 3; row++) {
for (int column = 1; column <= 3; column++) {
if (column == 2) {
continue;
}
System.out.println(row + ", " + column);
}
}
Output:
1, 1
1, 3
2, 1
2, 3
3, 1
3, 3
Only the column == 2 iteration of the inner loop is skipped.
Labeled break and continue
Labeled break
Java supports labels when you need to exit an outer loop from inside a nested loop:
search:
for (int row = 1; row <= 3; row++) {
for (int column = 1; column <= 3; column++) {
if (row == 2 && column == 3) {
break search;
}
System.out.println(row + ", " + column);
}
}
break search; terminates the labeled outer loop. As a beginner, you only need to recognize the concept. Using labels more than necessary can make control flow difficult to follow.
Labeled continue
Java also supports labeled continue to move to the next iteration of an outer loop:
outer:
for (int row = 1; row <= 3; row++) {
for (int column = 1; column <= 3; column++) {
if (column == 2) {
continue outer;
}
System.out.println(row + ", " + column);
}
}
Output:
1, 1
2, 1
3, 1
When column 2 is reached, the remaining work for the current row is skipped and the next row begins. Labeled control flow is uncommon. If the problem can be solved using simpler loop logic, prefer that approach.
Complete Example: Search First Match
public class Main {
public static void main(String[] args) {
String text = "Production Java";
char target = 'J';
int foundIndex = -1;
for (int index = 0; index < text.length(); index++) {
if (text.charAt(index) != target) {
continue;
}
foundIndex = index;
break;
}
if (foundIndex >= 0) {
System.out.println("Found at index: " + foundIndex);
} else {
System.out.println("Character not found");
}
}
}
Output:
Found at index: 11
Here:
- Non-matching character →
continue - Match found → store the index
- Remaining search is unnecessary →
break
When Should You Use break and continue?
Use break when the remaining iterations are unnecessary: a search result has been found, the user selected Exit, a sentinel arrived, or an intentional while (true) loop has reached its exit condition. Use continue to skip an item that should not be processed (filtering invalid values) and keep the main processing block free of extra nesting.
Do Not Overuse Them
A loop containing many break and continue statements can become difficult to follow. Hard to follow:
for (...) {
if (...) {
continue;
}
if (...) {
break;
}
if (...) {
continue;
}
}
Prefer:
- Clear conditions
- Meaningful boolean variables
- Small loop bodies
- Simple control flow
Predict the Result
Question 1
for (int number = 1; number <= 10; number++) {
if (number % 3 == 0) {
continue;
}
if (number > 7) {
break;
}
System.out.print(number + " ");
}
What does this print?
Answer
1 2 4 5 7 . continue skips 3 and 6. At 8 the condition number > 7 is true, so break ends the loop before 9 and 10 are reached.
Question 2
for (int row = 1; row <= 3; row++) {
for (int column = 1; column <= 3; column++) {
if (column == 2) {
break;
}
System.out.println(row + "," + column);
}
}
What does this print?
Answer
1,1
2,1
3,1
break exits only the innermost loop. The outer loop continues with the next row.
Question 3
for (int number = 1; number <= 3; number++) {
switch (number) {
case 2:
System.out.println("Two");
break;
default:
System.out.println(number);
}
}
What does this print?
Answer
1
Two
3
Inside a traditional switch, break leaves the switch, not the loop, so the loop still reaches 3.
Question 4
for (int number = 1; number <= 5; number++) {
if (number == 3) {
break;
System.out.println("Found 3");
}
}
Will it compile?
Answer
No: unreachable statement. Nothing after break in the same block can ever run, and Java reports that as an error.
Common Mistakes
Code After break or continue
Wrong:
if (number == 3) {
break;
System.out.println("Stopped");
}
The statement after break can never execute, so this code does not compile. javac reports error: unreachable statement. The same happens with a statement after continue. Put the statement before break:
if (number == 3) {
System.out.println("Stopped");
break;
}
Checking the Sentinel After Processing It
Wrong:
total += number;
if (number == -1) {
break;
}
This adds -1 to the total. Correct:
if (number == -1) {
break;
}
total += number;
Wrong continue Condition
Requirement:
Skip invalid marks.
Wrong:
if (mark >= 0 && mark <= 100) {
continue;
}
This skips valid marks. Correct:
if (mark < 0 || mark > 100) {
continue;
}
Practice Exercise 1: Stop Before Five
Solutions: lesson 1.25.
Run a loop from 1 to 10. Stop the loop when 5 is reached. Expected:
1
2
3
4
Practice Exercise 2: Include Five
Stop the loop after printing 5. Expected:
1
2
3
4
5
Practice Exercise 3: Skip Five
Print from 1 to 10, but do not print 5.
Practice Exercise 4: Even Numbers
Use continue to skip odd numbers from 1 to 20 and print only even numbers.
Practice Exercise 5: Character Search
String text = "Java Foundation";
Find the index of the first 'a' character and stop the loop as soon as a match is found.
Practice Exercise 6: Sentinel Total
The user enters numbers. When -1 is entered, stop the loop. Do not add the sentinel to the total.
Practice Exercise 7: Fix the Infinite Loop
int number = 1;
while (number <= 5) {
if (number == 3) {
continue;
}
System.out.println(number);
number++;
}
Explain the problem and fix it.
Practice Exercise 8: Nested break
Create a 3 × 3 nested loop. For each row, stop the inner loop when column 2 is reached. Expected:
1, 1
2, 1
3, 1
Practice Exercise 9: Labeled break
Inside a nested loop, exit both loops when the coordinate 2, 3 is found.
Practice Exercise 10: Filtering
Iterate through the numbers from 1 to 20. Skip numbers that are not divisible by 3, and print only the divisible numbers.
Knowledge Check
Question 1
What does break do?
Question 2
What does continue do?
Question 3
Does break terminate the entire program?
Question 4
Does continue terminate the entire loop?
Question 5
Why is break useful in a search loop?
Question 6
What executes after continue in a for loop?
Question 7
Why can continue cause an infinite loop in a while loop?
Question 8
Which loop does a normal break terminate in a nested loop?
Question 9
What does labeled break do?
Question 10
What does labeled continue do?
Question 11
When should a sentinel be checked?
Question 12
Which statement is useful for filtering invalid values?
Question 13
What is the main difference between break and continue?
Question 14
What problem can occur if break or continue is overused?
Knowledge Check Answers
Answer 1
It immediately terminates the nearest loop.
Answer 2
It skips the remaining statements of the current iteration and moves to the next iteration.
Answer 3
No. It terminates only the nearest loop.
Answer 4
No.
Answer 5
Once the target is found, unnecessary remaining iterations can be stopped.
Answer 6
The for loop's update expression executes, then the condition is checked again.
Answer 7
If the counter update appears after continue, that update can be skipped, causing the condition variable to remain stuck at the same value.
Answer 8
The nearest or innermost loop.
Answer 9
It can terminate execution up to a named outer loop.
Answer 10
It can start the next iteration of a named outer loop.
Answer 11
Before processing the sentinel as normal data.
Answer 12
continue;
Answer 13
break terminates the loop, while continue skips only the current iteration.
Answer 14
Control flow can become harder to read, debug, and maintain.
Lesson Summary
breakimmediately terminates the nearest loop; the program continues after the loop.continueskips the rest of the current iteration; in aforloop, the update runs next and the condition is checked again.breakis useful in search loops, for sentinels, and as the exit of an intentionalwhile (true)loop.continueis useful for skipping invalid values and keeping the main logic flat.- In a
whileloop, update the counter beforecontinue, or the update can be skipped and the loop never ends. - In nested loops, a normal
breakorcontinueaffects only the innermost loop. Labeledbreakandcontinuetarget an outer loop, but use them sparingly. - Check a sentinel before processing it, and avoid filling one loop with many
breakandcontinuestatements.
আগে ভাবুন
শীঘ্রই আসছেCheckpoint প্রশ্ন, যেখানে lesson উত্তর দেখানোর আগে আপনাকে একটি উত্তর বেছে নিতে হবে।