Break and Continue
The break
and continue
statements are used to control the flow of loops in Java. They allow you to either exit a loop early (break
) or skip the current iteration and move to the next one (continue
).
break
Statement
The break
statement is used to immediately terminate the closest enclosing loop (for
, while
, or do-while
) or switch
statement. Once the break
statement is encountered, the control exits the loop and proceeds with the next statement after the loop.
Syntax:
break;
Example:
In this example, the loop terminates when i == 3
.
for (int i = 0; i < 5; i++) {
if (i == 3) {
break; // Exit the loop when i equals 3
}
System.out.println(i);
}
Output:
0
1
2
continue
Statement
The continue
statement skips the current iteration of the loop and proceeds with the next iteration. Unlike break
, it does not terminate the loop; instead, it causes the loop to skip the remaining code in the current iteration and move to the next one.
Syntax:
continue;
Example: In this example, the loop skips the iteration when i is even.
for (int i = 0; i < 5; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
System.out.println(i);
}
Output:
1
3