๐ What Youโll Learn
- Exit loops or switch statements early using
break - Skip iterations in loops using
continue - Use labeled loops to control nested loop execution
- Avoid common mistakes when using these control statements
๐ช Break Statement
The break statement is used to exit a loop or switch block immediately.
Example: Exiting a Loop Early
for (int i = 1; i <= 5; i++) {
if (i == 3) break;
System.out.println(i);
}
Output:
1
2
When i becomes 3, the loop is terminated with break.
๐ Break in While Loops
You can use break in a while loop to stop it when a certain condition is met.
int i = 1;
while (i <= 10) {
if (i == 5) break;
System.out.println(i);
i++;
}
โก๏ธ Continue Statement
The continue statement skips the current iteration and proceeds to the next one in a loop.
Example: Skipping a Specific Value
for (int i = 1; i <= 5; i++) {
if (i == 3) continue;
System.out.println(i);
}
Output:
1
2
4
5
๐ Continue in While Loops
Hereโs how continue works in a while loop:
int i = 0;
while (i < 5) {
i++;
if (i == 3) continue;
System.out.println(i);
}
Output:
1
2
4
5
๐ฏ Labeled Loops
Labeled loops allow you to break or continue outer loops from within nested inner loops.
outer:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (j == 2) break outer;
System.out.println("i=" + i + ", j=" + j);
}
}
Output:
i=1, j=1
๐ Practical Use Cases
These statements are useful when you want to:
- Stop searching a list once a match is found
- Skip invalid input in user interaction loops
- Optimize performance by avoiding unnecessary operations
int[] numbers = {2, 4, 6, 8, 10};
for (int num : numbers) {
if (num == 6) {
System.out.println("Found 6!");
break;
}
}
โ ๏ธ Common Mistakes
- Forgetting to update loop variables, especially after
continue - Using
breakinappropriately and exiting too early - Mistaking
breakforreturn(which exits the whole method)
๐ Recap
- Use
breakto exit loops or switch blocks - Use
continueto skip iterations - Labeled loops offer control in nested scenarios
- Careful use improves logic clarity and performance