Labelled break statement in Java

In this tutorial, we will talk about the labelled break statement in Java. In Java, we can use a label with the break statement. This label indicates which loop to exit. Labels can be very useful when used with the break statements. We will see some examples to understand the labelled break statement in this post.

Normally, we use a break statement to exit a loop. We can specify some condition to break the loop. In the below example, we are using a for loop in Java to print numbers from 1 to 10. Notice that we have used a break statement when the value of the variable that stores these numbers becomes 5. Hence the loop breaks and prints numbers only up to 5. See the code.

public class Main
{
  public static void main(String[] args) {
      int i;
    for(i=1; i<=10; i++)
    {
        System.out.println(i);
        if(i == 5)
            break;
    }
  }
}

Output:

1
2
3
4
5

Now, let’s see another example which involves the use of label with the break statement. Have a look at the given code.

public class Main
{
  public static void main(String[] args) {
      int i;
      outer:
    for(i=1; i<5; i++)
    {
        int j;
        inner:
        for(j=1; j<5; j++)
        {
            System.out.println("Inner Loop.");
            if(j==3)
                break outer;
        }
        System.out.println("Outer Loop.");
    }
    System.out.println("Outside of the outer loop.");
  }
}

Output:

Inner Loop.
Inner Loop.
Inner Loop.
Outside of the outer loop.

Let’s understand the code step by step. As you can see, we have used two loops, outer loop and inner loop. We have used outer and inner labels for these loops. In the program, we have used the break statement with the outer label (At this moment we are inside the inner loop). Which is why the control of the execution moves from the inner loop to directly outside of the loop. And therefore, the program does not print “Outer Loop”, as this statement is never executed.

Hope you understood.

Thank you.

Also read: Exit from a loop in Java with examples

 

Leave a Reply

Your email address will not be published. Required fields are marked *