Java Labeled break Statement

ww‮itfigi.w‬dea.com

In Java, a labeled break statement allows you to terminate an outer loop from within an inner loop. It is useful when you have nested loops and you want to exit both loops when a certain condition is met. Here's the basic syntax of a labeled break statement in Java:

labelName: {
    // code block
    break labelName;
    // more code
}

The labelName is a user-defined identifier that you place before the loop statement you want to break out of. The break statement inside the block transfers the control to the statement immediately following the labeled block.

Here's an example of a labeled break statement:

outerloop: for (int i = 1; i <= 3; i++) {
    innerloop: for (int j = 1; j <= 3; j++) {
        if (i == 2 && j == 2) {
            break outerloop;
        }
        System.out.println("i = " + i + ", j = " + j);
    }
}

In this code, the outer loop has a label called outerloop, and the inner loop has a label called innerloop. When the condition i == 2 && j == 2 is met, the break statement with the label outerloop is executed, which terminates the outer loop and continues with the statement after the labeled block.

Without the labeled break statement, only the inner loop would be terminated, and the outer loop would continue to iterate. However, with the labeled break statement, both loops are terminated when the condition is met.