Breaking Out of Loops

In all of the loops, the loop ends when a tested condition is met. There might be times when something occurs during execution of a loop and you want to exit the loop early. For that you can use the break and continue keywords.

You already have seen break as part of the switch statement; break stops execution of the switch statement, and the program continues. The break keyword, when used with a loop, does the same thing—it immediately halts execution of the current loop. If you have nested loops within loops, execution picks up with the next outer loop. Otherwise, the program merely continues executing the next statement after the loop.

For example, recall the while loop that copied elements from an integer array into an ...

Get Sams Teach Yourself Java 2 in 21 Days, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.