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.
break exits a labeled block or loopcontinue skips to the next iteration of a labeled loopA labeled statement is written before a loop or block and can be referenced later using break or continue.
// Syntax of a labeled loop in Java
labelName:
for(int i = 0; i < 5; i++) {
System.out.println(i);
}
// 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);
}
}
When i == 2 and j == 2, the break outerLoop; statement stops both loops immediately. Without a label, only the inner loop would terminate.
breakbreak with continue and observe behaviorwhile loops