Java Break
The break
statement is super useful when you need to exit a loop early or skip over some unnecessary steps. You’ve probably seen it in switch statements before, but it works wonders in loops too.
Here’s an example that stops the loop when the variable counter
hits 4:
for (int counter = 0; counter < 10; counter++) { if (counter == 4) { break; } System.out.println("Counter: " + counter); }
Java Continue
The continue
statement is great for skipping the current iteration of a loop and moving straight to the next one. This can be handy when you want to bypass certain conditions.
For example, this code skips printing the value 4:
for (int counter = 0; counter < 10; counter++) { if (counter == 4) { continue; } System.out.println("Counter: " + counter); }
Break and Continue in While Loops
You can use break
and continue
in while
loops as well. Here are some examples:
Break Example in a While Loop
This loop stops when the variable index
reaches 4:
int index = 0; while (index < 10) { System.out.println("Index: " + index); index++; if (index == 4) { break; } }
Continue Example in a While Loop
This loop skips the iteration when index
is 4 and continues with the next one:
int index = 0; while (index < 10) { if (index == 4) { index++; continue; } System.out.println("Index: " + index); index++; }
Extra Tidbits
- Nested Loops: You can use
break
to get out of nested loops. If you need to exit multiple loops at once, labeled loops can be handy. - Better Control: Combining
break
andcontinue
withif-else
statements gives you more control over your loops. - Efficiency: Using these statements wisely can help optimize loop performance by giving you finer control over when to stop or skip iterations.