Labeled Break Keyword in Java for loop Example

Labeled Break Keyword in Java : –

Table of Contents

In Java, the labeled break statement is used to terminate a loop or switch statement based on a specified label. It allows you to break out of nested loops or switch statements and jump to a specific point in the code.

Here’s the syntax for using labeled break in Java:

public class A   {
public static void main(String[] args) {
	for (int i=0; i<5; i++) {
	x: if (i==2) {
		break x;
	}
	System.out.println(i);
}
}
}
Output :
0
1
2
3
4
public class A   {
public static void main(String[] args) {

	x:for (int i=0; i<5; i++) {
	 if (i==2) {
		break x;
	}
	
	
	System.out.println(i);
	}
}
}
Output : 
0
1

Labeled Break Keyword in Java

Here’s an example of using labeled break with a nested loop:

outerloop:
for (int i = 0; i < 5; i++) {
   for (int j = 0; j < 5; j++) {
      if (i * j > 6) {
         System.out.println("Breaking");
         break outerloop;
      }
      System.out.println(i + " " + j);
   }
}
System.out.println("Done");

In this example, the outer loop is labeled as outerloop. When the condition i * j > 6 is true, the labeled break statement is executed, causing the program to jump out of the outer loop and continue with the next line of code after the labeled block. The output of this code would be:

output:

0 0
0 1
0 2
0 3
0 4
1 0
1 1
1 2
1 3
Breaking
Done

Note that the loop does not complete all 25 iterations because the labeled break statement causes it to exit early.

Break vs Continue in java

In Java, break and continue are two control flow statements that can be used inside loops to modify the flow of execution.

break is used to terminate the loop or switch statement it is located in. When executed, break causes the program to exit the loop and continue executing the next statement after the loop. Here’s an example:

for (int i = 0; i < 10; i++) {
   if (i == 5) {
      break;
   }
   System.out.println(i);
}

In this example, the loop will iterate 5 times, printing the values of i from 0 to 4, then it will terminate because i becomes 5 and the break statement is executed. The output of this code would be:

0
1
2
3
4

continue, on the other hand, skips the current iteration of the loop and moves on to the next iteration. It does not terminate the loop, but rather jumps back to the top of the loop and starts the next iteration. Here’s an example:

for (int i = 0; i < 10; i++) {
   if (i % 2 == 0) {
      continue;
   }
   System.out.println(i);
}

In this example, the loop will iterate 10 times, but only print the values of i that are odd, skipping the even numbers. The output of this code would be:

1
3
5
7
9

In summary, break is used to terminate the loop or switch statement, while continue is used to skip the current iteration and move on to the next one. Both statements can be useful for modifying the flow of execution inside loops.

Leave a Comment