Naming a Loop

Like other statements in Java programs, loops can be put inside of each other. The following shows a for loop inside a while loop:

int points = 0;
int target = 100;
while (target <= 100) {
    for (int i = 0; i < target; i++) {
        if (points > 50)
            break;
        points = points + i;
    }
}

In this example, the break statement will cause the for loop to end if the points variable is greater than 50. However, the while loop will never end, because target is never greater than 100.

In this case (and others), you might want to break out of both loops. To make this possible, you have to give the outer loop—in this example, the while statement—a name. To name a loop, put the name on the line before the beginning of the loop and follow it with a colon ...

Get SAMS Teach Yourself Programming with Java™ in 24 Hours, FOURTH 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.