Labeled For Loop in Java Programming Language
Table of Content:
Labeled For Loop
We can have name of each for loop. To do so, we use label before the for loop. It is useful if we have nested for loop so that we can break/continue specific for loop.
According to nested loop, if we put break statement in inner loop, compiler will jump out from inner loop and continue the outer loop again. What if we need to jump out from the outer loop using break statement given inside inner loop? The answer is, we should define lable along with colon(:) sign before loop.
Syntax:
labelname: for(initialization;condition;incr/decr){ //code to be executed }
Example without labelled loop
//WithoutLabelledLoop.java class WithoutLabelledLoop { public static void main(String args[]) { int i,j; for(i=1;i<=10;i++) { System.out.println(); for(j=1;j<=10;j++) { System.out.print(j + " "); if(j==5) break; //Statement 1 } } } }
Output:
1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 Press any key to continue . . .
In th above example, statement 1 will break the inner loop and jump outside from inner loop to execute outer loop.
Example with labelled loop
//WithLabelledLoop.java class WithLabelledLoop { public static void main(String args[]) { int i,j; loop1: for(i=1;i<=10;i++) { System.out.println(); loop2: for(j=1;j<=10;j++) { System.out.print(j + " "); if(j==5) break loop1; //Statement 1 } } } }
Output:
1 2 3 4 5 Press any key to continue . . .