Break and continue are jump statements used to alter the normal flow of loops. They help control loop execution by either terminating the loop early or skipping specific iterations. These statements can be used inside for, while, and do-while loops.
Break
The break statement in Java is used to immediately terminate a loop or switch statement and transfer control to the statement following it.
- Exits a loop before its condition becomes false
- Terminates execution when a specific condition is met
- Used to exit a switch case or break out of labeled (nested) loops
Syntax
break;
Example 1: Using break to exit a loop
Using break, we can force immediate termination of a loop, bypassing the conditional expression and any remaining code in the body of the loop. When we use break inside the nested loops, it will only break out of the innermost loop.
class GFG {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if (i == 5)
break;
System.out.println("i: " + i);
}
System.out.println("Out of Loop");
}
}
Output
i: 0 i: 1 i: 2 i: 3 i: 4 Out of Loop
Explanation: The loop terminates as soon as i becomes 5, without checking further conditions.
Continue
The continue statement in Java is used to skip the current iteration of a loop and move directly to the next iteration.
- Skips specific values or conditions within a loop
- Avoids executing remaining statements in the current iteration
- Improves readability when filtering data in loops
Syntax
continue;
Example 1: Using continue to skip an iteration
class GFG {
public static void main(String args[]) {
for (int i = 0; i < 10; i++) {
if (i == 2)
continue;
System.out.print(i + " ");
}
}
}
Output
0 1 3 4 5 6 7 8 9
Explanation: When i equals 2, the iteration is skipped and the loop continues with the next value.
Difference between break and continue:
Break | Continue |
|---|---|
Terminates the loop immediately. | Skips the current iteration and continues with the next one |
Transfers control outside the loop. | Transfers control to the next loop iteration. |
Can be used with loops and switch statements. | Can be used only inside loops. |
Stops further execution of the loop body completely. | Skips only the remaining statements in the current iteration. |
Can be used with labeled loops. | Can also be used with labeled loops. |