< Prev
Next >



Labelled Break Statement





In Labelled Break Statement, we give a label/name to a loop.

When this break statement is encountered with the label/name of the loop, it skips the execution any statement after it and takes the control right out of this labelled loop.

And, the control goes to the first statement right after the loop.





Labelled break statement example with while loop


//Labelled break example with while loop
 
public class LabelledBreak
{
public static void main(String... ar)
{

int i=7;

loop1:
while(i<20)
{	
	if(i==10)
		break loop1;

	System.out.println("i ="+i); 
	i++;
}

System.out.println("Out of the loop");

} //main method ends

} //class ends


Output


7
8
9
Out of the loop





Labelled break statement example with nested for loop


 //Labelled break example with nested for loop

public class LabelledBreak
{
public static void main(String... ar)
{


loop2:
for(int i=0;i<2;i++)
for(int j=0;j<5;j++)
{	
	if(j==2)
		break loop2;

	System.out.println("i = "+i);
	System.out.println("j = "+j);
}

System.out.println("Out of the loop");

} //main method ends

} //class ends


Output


i = 0
j = 0
i = 0
j = 1
Out of the loop

As you may see in the example, outer for-loop was named loop2. When the labelled break statement was encountered during the iteration, i equals to 0 and j equals to 2, it broke the loop and skipped executing the two print statements in the loop and after it and finally the print statement, System.out.println() is executed.



Please share this article -

Facebook Google Pinterest Reddit Tumblr Twitter




< Prev
Next >
< Continue Statement
Labelled Continue Statement>
Please subscribe our social media channels for notifications, we post a new article everyday.

Decodejava Google+ Page Decodejava Facebook Page  DecodeJava Twitter Page

Coming Next
-
C++ and Python

Ad2