Differentiate between simple loop and labelled loop in Java. Explain with example.
Answers
Answer:
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 of Labelled loop
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
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
In th above example, statement 1 will break the inner loop and jump outside the outer loop.