Labeled Loops

Labeled loops provide a way to control the flow of nested loops more precisely, especially when there are multiple levels of loops. With labeled loops, you can specify which loop to break out of or continue, making it easier to manage complex control flows.

How Labeled Loops Work

To use a labeled loop, you assign a label to a specific loop by placing an identifier (the label) before it, followed by a colon (:). Then, when using break or continue, you refer to that label to break or continue the labeled loop rather than just the innermost loop.

Syntax of Labeled Loops

outerLoop: // This is a label for the outer loop
for (int i = 0; i < 5; i++) {
    for (int j = 0; j < 5; j++) {
        if (condition) {
            break outerLoop; // Exits the outer loop
        }
    }
}

In this example, if condition is met, break outerLoop will exit the outerLoop, not just the inner for loop.

Common Use Cases

  1. Exiting Multiple Loops: Labeled break allows you to exit multiple levels of loops when a specific condition is met.
  2. Skipping Iterations in Outer Loops: Labeled continue skips the current iteration of the labeled loop, allowing you to bypass code in multiple levels when a condition is met.

Example of break with a Labeled Loop

outerLoop:
for (int i = 0; i < 5; i++) {
    for (int j = 0; j < 5; j++) {
        System.out.println("i = " + i + ", j = " + j);
        if (i == 2 && j == 3) {
            break outerLoop; // Exits the outer loop labeled "outerLoop"
        }
    }
}

Example of continue with a Labeled Loop

outerLoop:
for (int i = 0; i < 5; i++) {
    for (int j = 0; j < 5; j++) {
        if (j == 2) {
            continue outerLoop; // Skips to the next iteration of the outer loop
        }
        System.out.println("i = " + i + ", j = " + j);
    }
}

In this case, when j == 2, continue outerLoop skips to the next iteration of i in the outerLoop.

Benefits of Labeled Loops

Labeled loops can make code more readable by clearly indicating which loop is being broken or continued, especially in complex scenarios with multiple nested loops. They also prevent the need for additional if statements or flags to manage flow in such cases, reducing code complexity.

Caution

While labeled loops can simplify certain scenarios, they may also make code harder to follow if overused. Therefore, use them judiciously and prioritize readability.