π 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
break
inappropriately and exiting too early - Mistaking
break
forreturn
(which exits the whole method)
π Recap
- Use
break
to exit loops or switch blocks - Use
continue
to skip iterations - Labeled loops offer control in nested scenarios
- Careful use improves logic clarity and performance