The break and continue statements are used to control the flow of execution in loops and switch statements.
The break statement is used to exit a loop or switch statement early. When a break statement is encountered inside a loop or switch statement, control jumps immediately to the statement following the loop or switch. Here’s an example of using the break statement to exit a loop early:
for (int i = 0; i < 10; i++) {
if (i == 5) {
break;
}
System.out.println(i);
}
In this example, we have a for loop that iterates over the values of i
from 0 to 9. Inside the loop, we have an if statement that checks if i
is equal to 5. If it is, we use the break statement to exit the loop early. As a result, only the values of i
from 0 to 4 will be printed.
The continue statement is used to skip the current iteration of a loop and jump to the next iteration. When a continue statement is encountered inside a loop, control jumps immediately to the loop condition and the next iteration of the loop begins. Here’s an example of using the continue statement to skip even values of i
:
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue;
}
System.out.println(i);
}
In this example, we have a for loop that iterates over the values of i
from 0 to 9. Inside the loop, we have an if statement that checks if i
is even (i.e., divisible by 2). If it is, we use the continue statement to skip the current iteration of the loop. As a result, only the odd values of i
will be printed.
Both the break and continue statements are useful constructs for controlling the flow of execution in loops and switch statements. However, they should be used judiciously to avoid creating code that is hard to read and maintain.