Wednesday, March 23, 2022

Labelled Loops in Java

Labelling a for loop is helpful when we are in need to break or continue a specific for loop based on the requirement. We know that we put a break statement inside an inner loop, then the compiler will jump out of the inner loop and continue with the outer loop again. But what if we need to jump out from the outer loop using the break statement given inside the inner loop? In such cases labelled loops becomes handy. Check the example below:

OUTER:
for (int i = 0; i < 10; i++) {
  System.out.print(i + " ");
  INNER:
  for (int j = 100; j < 105; j++) {
    System.out.print(j + " ");
    if (i == 4 && j == 103) break OUTER;
  }
  System.out.println("");
}

//output
0 100 101 102 103 104 
1 100 101 102 103 104 
2 100 101 102 103 104 
3 100 101 102 103 104 
4 100 101 102 103

No comments:

Post a Comment