What are break and continue?
In Java, break and continue are loop control statements.
They are used to change the normal flow of loops (for, while, do-while, and switch).
-
break→ stops the loop completely -
continue→ skips the current iteration and moves to the next one
The break Statement
What is break?
The break statement is used to terminate a loop immediately when a specific condition is met.
Once break is executed:
- The loop stops
- Control moves to the statement after the loop
Syntax of break
break;
Example: Using break in a loop
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break;
}
System.out.println(i);
}
Output:
1
2
3
4
Explanation:
The loop starts from 1. When i becomes 5, the break statement executes and stops the loop completely. Numbers after 4 are not printed.
Using break in a switch Statement
int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
default:
System.out.println("Invalid day");
}
Explanation:
break prevents execution from falling into the next case. Without break, multiple cases would execute.
The continue Statement
What is continue?
The continue statement is used to skip the current iteration of a loop and move to the next iteration.
Unlike break:
- The loop does not stop
- Only the current iteration is skipped
Syntax of continue
continue;
Example: Using continue in a loop
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
System.out.println(i);
}
Output:
1
2
4
5
Explanation:
When i becomes 3, the continue statement skips printing 3 and moves to the next iteration. The loop continues normally.
break vs continue
| Feature | break | continue |
|---|---|---|
| Stops loop | Yes | No |
| Skips iteration | No | Yes |
| Control moves to | After loop | Next iteration |
| Used in switch | Yes | No |
Important Points to Note
-
breakexits the loop completely -
continueskips only the current iteration - Both improve loop control and readability
- Used with conditional statements (
if) - Helps avoid unnecessary execution
Common Use Cases
break is used when:
- A value is found in a search
- Input validation fails
- Loop should stop early
continue is used when:
- Certain values should be ignored
- Filtering even or odd numbers
- Skipping invalid data
Example: Using break and continue Together
for (int i = 1; i <= 10; i++) {
if (i == 3) {
continue;
}
if (i == 8) {
break;
}
System.out.println(i);
}
Output:
1
2
4
5
6
7
Explanation:
-
continueskips printing 3 -
breakstops the loop whenireaches 8
Common Mistakes to Avoid
- Forgetting
breakinswitchcases - Using
continuewithout understanding loop flow - Creating infinite loops accidentally
- Confusing
breakandcontinuebehavior
When to Use break and continue?
Use these statements when:
- You need better control over loops
- Certain conditions require early exit
- Some iterations should be skipped
- Writing clean and efficient logic
Top comments (0)