1. Introduction
In Java, break and continue are two important control flow statements used within loops. break is used to exit the loop entirely, skipping any remaining iterations. continue, on the other hand, is used to skip the current iteration and proceed with the next iteration of the loop.
2. Key Points
1. break terminates the loop immediately, and control resumes at the first statement following the loop.
2. continue skips the current iteration and move to the end of the loop body, proceeding with the next iteration.
3. break can be used in all types of loops as well as in switch statements.
4. continue is only used in loops and cannot be used in switch statements.
3. Differences
break | continue |
---|---|
Used to exit from the loop immediately, regardless of its condition. | Skips the rest of the code inside the loop for the current iteration and jumps to the next iteration of the loop. |
It can be used in loops (for, while, and do-while) and switch statements. | It is only used in loops (for, while, and do-while); it cannot be used in switch statements. |
After executing a break statement, the control moves to the statement immediately following the loop or switch. | After a continue statement is executed, the control moves to the beginning of the loop for the next iteration, skipping the remaining code in the loop body for the current iteration. |
Used to terminate the loop or to exit from a switch case. | Used to skip the current iteration based on a specific condition without terminating the loop. |
It can be used to escape early from a loop when a certain condition is met, avoiding unnecessary or irrelevant further iterations. | This is used when you want to avoid the current iteration due to a specific condition but still continue looping through the remaining iterations. |
4. Example
// Example of break
System.out.println("Example of break:");
for (int i = 1; i <= 5; i++) {
// If the value of i is 3, break out of the loop
if (i == 3) {
break;
}
System.out.println(i);
}
// Example of continue
System.out.println("\nExample of continue:");
for (int i = 1; i <= 5; i++) {
// If the value of i is 3, skip this iteration
if (i == 3) {
continue;
}
System.out.println(i);
}
Output:
Example of break: 1 2 Example of continue: 1 2 4 5
Explanation:
1. In the break example, the loop prints numbers 1 and 2, and as soon as it reaches 3, the break statement terminates the loop.
2. In the continue example, the loop prints numbers 1 and 2, skips number 3 due to the continue statement, and then resumes by printing numbers 4 and 5.
5. When to use?
- Use break when you need to exit a loop immediately based on a certain condition or to terminate a switch statement.
- Use continue when you want to skip the rest of the current loop iteration and continue with the next iteration.
Comments
Post a Comment
Leave Comment