Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

A labeled statement in Java is an identifier followed by a colon (:) that prefixes a statement, providing a named target for the execution control flow jump instructions break and continue. It allows the explicit routing of execution flow to a specific enclosing block or loop, bypassing the default behavior of targeting the innermost construct.

Syntax

labelIdentifier: statement;
The labelIdentifier must be a valid Java identifier. The statement can be any valid Java statement, though labels are almost exclusively applied to loops (for, while, do-while) or block statements ({ ... }).

Technical Mechanics and Rules

  • Scope: The scope of a label is strictly limited to the statement it directly precedes. A label cannot be referenced by a break or continue statement located outside of the labeled statement’s execution block.
  • Namespace: Labels occupy a distinct namespace in the Java compiler. A label can share a name with a variable, method, or class in the same scope without causing a compilation error.
  • Shadowing: A label cannot be declared if an enclosing labeled statement already uses the same identifier. Label shadowing is prohibited and results in a compile-time error.
  • Targeting Constraints:
    • A labeled break can target any enclosing labeled statement (including standard blocks).
    • A labeled continue can only target an enclosing labeled loop. Attempting to use continue on a labeled non-loop block results in a compilation error.

Control Flow Interaction

Labeled break

When break labelIdentifier; is executed, the JVM immediately terminates the execution of the block associated with labelIdentifier. Control flow is transferred to the first statement immediately following the terminated block.
outerBlock: {
    System.out.println("Entering outer block");
    
    innerBlock: {
        System.out.println("Entering inner block");
        break outerBlock; // Terminates outerBlock entirely
        // Unreachable code
    }
    
    // Unreachable code
}
// Execution resumes here after the break

Labeled continue

When continue labelIdentifier; is executed, the JVM skips the remaining statements in the current iteration of the innermost loop, as well as any intermediate enclosing loops, up to the loop associated with labelIdentifier. Control flow is transferred to the update expression (in a for loop) or the boolean evaluation (in a while/do-while loop) of the targeted loop to begin its next iteration.
outerLoop: for (int i = 0; i < 5; i++) {
    innerLoop: for (int j = 0; j < 5; j++) {
        if (j == 2) {
            continue outerLoop; // Skips remaining innerLoop iterations and jumps to i++
        }
    }
}
Master Java with Deep Grasping Methodology!Learn More