Java Labeled continue Statement
In Java, a labeled continue
statement allows you to skip the current iteration of an outer loop from within an inner loop. It is useful when you have nested loops and you want to skip the current iteration of an outer loop based on a condition within an inner loop. Here's the basic syntax of a labeled continue
statement in Java:
labelName: { // code block continue labelName; // more code }
The labelName
is a user-defined identifier that you place before the loop statement you want to continue. The continue
statement inside the block transfers the control to the loop condition of the labeled block.
Here's an example of a labeled continue
statement:
outerloop: for (int i = 1; i <= 3; i++) { innerloop: for (int j = 1; j <= 3; j++) { if (i == 2 && j == 2) { continue 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 continue
statement with the label outerloop
is executed, which skips the current iteration of the outer loop and continues with the next iteration of the outer loop.
Without the labeled continue
statement, only the inner loop would skip the current iteration, and the outer loop would continue to iterate. However, with the labeled continue
statement, the current iteration of both loops is skipped when the condition is met.