Next: On the usefulness thereof. Up: More about loops. Previous: The continue statement.


Labeled break and continue statements

Textbook: Section 8.5

What happens when you have one loop within another, and within the inner loop you want to break out of both? If you just type ``break,'' the computer will stop executing the inner loop and continue through the iteration of the outer loop.

The solution is the labeled break statement, which allows you to give a loop a name, which can then be named when you do the break. The following code searches an array to see if it has any duplicates.

    boolean has_duplicate = false;
outer_loop:
    for(int i = 0; i < arr.length; i++) {
        for(int j = i + 1; j < arr.length; j++) {
            if(arr[i] == arr[j]) {
                has_duplicate = true;
                break outer_loop;
            }
        }
    }

You can do the same sort of thing with continue statements, where you label the loop of which you wish to go to the next iteration.


Next: On the usefulness thereof. Up: More about loops. Previous: The continue statement.