← Back to Chapters

Java Labeled Statements

?️ Java Labeled Statements

? Quick Overview

Labeled statements in Java allow you to assign a name (label) to a loop or block. These labels are mainly used with break and continue statements to control nested loops more precisely.

? Key Concepts

  • A label is an identifier followed by a colon
  • Labels are commonly used with nested loops
  • break exits a labeled block or loop
  • continue skips to the next iteration of a labeled loop

? Syntax / Theory

A labeled statement is written before a loop or block and can be referenced later using break or continue.

? View Code Example
// Syntax of a labeled loop in Java
labelName:
for(int i = 0; i < 5; i++) {
    System.out.println(i);
}

? Code Example – break with Label

? View Code Example
// Demonstrates breaking out of an outer loop using a label
outerLoop:
for(int i = 1; i <= 3; i++) {
    for(int j = 1; j <= 3; j++) {
        if(i == 2 && j == 2) {
            break outerLoop;
        }
        System.out.println("i=" + i + ", j=" + j);
    }
}

? Live Output / Explanation

Explanation

When i == 2 and j == 2, the break outerLoop; statement stops both loops immediately. Without a label, only the inner loop would terminate.

? Tips & Best Practices

  • Use labels only when working with deeply nested loops
  • Choose meaningful label names for readability
  • Avoid excessive use to keep code maintainable
  • Labels cannot jump into arbitrary blocks

? Try It Yourself

  • Create a labeled loop and exit it using break
  • Replace break with continue and observe behavior
  • Try using labels with while loops