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 |
---|---|
Exits the loop immediately. | Skips to the next iteration of the loop. |
Used to escape the loop regardless of the condition. | This causes the loop to continue with the next iteration based on the condition. |
Can be used in both loops and switch statements. | Can only be used in loops. |
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