Java Notes
Break exits a loop or switch immediately, while continue skips the remaining work in only the current loop iteration.
break and continue change the normal flow of a loop. Use them for a clear, local reason; do not use them to hide complicated loop logic.
break: leave immediately
break exits the nearest loop or switch statement immediately.
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
After Java finds 91, break exits the loop. The final value, 74, is never examined.
continue: skip only this iteration
continue skips the remaining statements in the current iteration and starts the next one.
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
The loop still visits every number. It simply skips the print statement for even numbers.
break in switch
Traditional switch statements use break to stop Java from falling through into the next case.
Modern arrow-style switch cases do not need break, because each arrow case does not fall through.
Labeled break: rare but valid
A label lets break leave an outer loop. It is useful occasionally when a nested search is complete.
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Use labels sparingly. If a labeled break makes a method hard to follow, move the search into a separate method and return the result instead.
What to remember
breakexits the nearest loop or switch immediately.continueskips to the next loop iteration.- In a traditional switch,
breakprevents accidental fall-through. - A labeled break can leave an outer loop, but a small method is often clearer.
Continue the lesson path