In Java, labeled loops are a way to give a name (label) to a loop, allowing you to control the flow of execution in nested loops. This is especially useful when you want to break out of or continue a specific outer loop from within an inner loop. Labels are essentially identifiers that you place before a loop statement.
### Syntax of Labeled Loops
A label is followed by a colon (`:`) and precedes a loop statement. The general syntax is:
//java
labelName: {
// Loop statements
// Nested loops or other statements
}
//
### Usage of Labeled Loops
Labels can be used with the `break` and `continue` statements to control the flow of nested loops:
1. **Labeled `break` Statement**
The `break` statement can be used to exit from the loop that matches the label. This is useful when you want to exit from multiple nested loops.
**Example:**
//java
public class LabeledBreakExample {
public static void main(String[] args) {
outerLoop: // Label for the outer loop
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (i * j > 10) {
break outerLoop; // Breaks out of the outer loop
}
System.out.println(“i: ” + i + “, j: ” + j);
}
}
System.out.println(“Exited outer loop”);
}
}
//
In this example, the `break outerLoop` statement exits both the inner and outer loops when the condition `i * j > 10` is met.
2. **Labeled `continue` Statement**
The `continue` statement can be used to skip the current iteration of the loop that matches the label and continue with the next iteration of that loop.
**Example:**
//java
public class LabeledContinueExample {
public static void main(String[] args) {
outerLoop: // Label for the outer loop
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (i * j < 5) {
continue outerLoop; // Continues with the next iteration of the outer loop
}
System.out.println(“i: ” + i + “, j: ” + j);
}
}
System.out.println(“Finished processing”);
}
}
//
In this example, the `continue outerLoop` statement skips the remaining code in the inner loop and continues with the next iteration of the outer loop when the condition `i * j < 5` is met.
### Summary
– **Labeled loops** are used to give names to loops and provide more control over the flow of nested loops.
– **Labeled `break`** exits the labeled loop (and any nested loops) when encountered.
– **Labeled `continue`** skips the current iteration of the labeled loop and proceeds with the next iteration.
Labeled loops can be useful for managing complex looping scenarios, but they should be used judiciously to avoid making code less readable.
Leave a Reply