3.4 Break and Continue
In Java, break
and continue
are control flow statements that allow you to alter the normal flow of loops. They are particularly useful for managing iterations in for
, while
, and do-while
loops.
The break
Statement
The break
statement is used to exit a loop prematurely. When encountered, it immediately terminates the loop and transfers control to the statement following the loop.
Syntax
break;
Example
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exit the loop when i equals 5
}
System.out.println(i);
}
Output:
1
2
3
4
In this example, the loop stops when i
equals 5, and the numbers 1 through 4 are printed.
The continue
Statement
The continue
statement skips the current iteration of the loop and moves to the next iteration. It does not terminate the loop but allows you to skip specific cases.
Syntax:
continue;
Example:
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
System.out.println(i);
}
Output:
1
3
5
7
9
In this example, the loop skips even numbers and prints only odd numbers.
Using break
and continue
in while
Loops
Example with break
int i = 1;
while (i <= 10) {
if (i == 5) {
break; // Exit the loop when i equals 5
}
System.out.println(i);
i++;
}
Output:
1
2
3
4
Example with continue
int i = 0;
while (i < 10) {
i++;
if (i % 2 == 0) {
continue; // Skip even numbers
}
System.out.println(i);
}
Output:
1
3
5
7
9
Key Points
break
: Use to exit a loop entirely.continue
: Use to skip the current iteration and proceed to the next.- Readability: Use these statements sparingly to maintain code clarity.
- Nested Loops: In nested loops,
break
andcontinue
affect only the innermost loop.
Common Pitfalls
- Infinite Loops: Ensure
break
orcontinue
does not cause unintended infinite loops. - Logic Errors: Misusing
break
orcontinue
can lead to unexpected behavior. Test thoroughly.
break
and continue
are powerful tools for controlling loop execution. Use them wisely to write efficient and readable code.