Labeled statements

Syntax

>>-Identifier-:-Statement-><

Description
Statements may have label prefixes. The Identifier is declared to be the label of the immediately contained Statement. Unlike C and C++, the Java language has no goto statement; identifier statement labels are used with break or continue statements appearing anywhere within the labeled statement. A statement that is labeled by an identifier must not appear anywhere within another statement that is labeled by the same identifier; otherwise a compilation error will occur. Two statements can be labeled by the same identifier only if neither statement contains the other.

There is no restriction against using the same identifier as a label and as the name of a package, class, interface, method, field, parameter, or local variable. Use of an identifier to label a statement does not hide a package, class, interface, method, field, parameter, or local variable with the same name.

Use of an identifier as a local variable or as the parameter of an exception handler does not hide a statement label with the same name. A labeled statement is executed by executing the immediately contained Statement. If the statement is labeled by an Identifier and the contained Statement completes abruptly because of a break with the same Identifier, then the labeled statement completes normally. In all other cases of abrupt completion of the Statement, the labeled statement completes abruptly for the same reason.

Example
The following example shows two nested while loops. Each loop has a label.

OuterWhile : while (true) {
    // do something interesting

    InnerWhile : while (true) {
        // do something else interesting

        /* 
         * stop this iteration of the InnerWhile loop and
         * begin the next one
         */
        if (someCondition) {
            continue InnerWhile;
        }

        /*
         * break out of the InnerWhile loop and continue 
         * the OuterWhile loop
         */
        if (breakCondition) {
            break OuterWhile;
        }

    } // InnerWhile
} // OuterWhile

ngrelr.gif (548 bytes)
Syntax diagrams
break keyword
continue keyword

Source: The Java Language Specification. Copyright (C) 1996 Sun Microsystems, Inc.