We're taking a leap today to learn break
and continue
, our control tools in Java loops. break
works as an exit, allowing you to leave a loop early, while continue
assists in skipping unneeded iterations. Let's get started!
Think of the break
command as representing the moment the music stops during a game of musical chairs, prompting you to exit the loop. It ends the loop regardless of the loop's original condition.
Here is a quick example:
Our loop operates on numbers from 0 to 6 and breaks when it reaches 7, taking an early exit and skipping all remaining iterations.
The keyword continue
in Java is analogous to skipping a boring view during a walk. It disregards the current loop iteration and jumps ahead to the next one.
Here is an example:
