Exit from a loop in Java with examples

Hello everyone, in this post, we are going to learn how to exit from a loop in Java. As in many other programming languages, in Java too, we have loops that we can use to execute a set of statements as long as a given condition is True.

Normally, a Java loop exits when the specified condition evaluates to false. That is one way of exiting the loop. Another way to exit a loop in Java is a break statement. We will see how it is used in a Java Program further in this tutorial.

Break statement in Java

There are two ways we can use a break statement in our Java Program while exiting from a loop. These are explained here.

With label

A break statement can be used to transfer the execution to the outside of a loop as shown in the below example program. To do this, we specify a label (A label represents a block of code). When the break statement is executed, the control transfers to the end of the block specified by the label. See the below code.

class Example{
  public static void main(String args[])
  {
    int i;
    here:
    for( i=0; i<5; i++)
    {
      System.out.println(i + "\n");
      if (i == 3)
        break here;
    }
  
  }
}

Output:

0

1

2

3

As you can notice in the program, we have specified a label ‘here’. And in the for loop, we are using a break statement when i equals 3 that transfers the execution to the end of the block specified by ‘here’ which is the for loop. Hence the output only contains 0, 1, 2 and 3.

Without label

We can use the break statement without any label. In this case, the loop is exited and the control of execution is transferred to the next statement just after the loop. See the below code to grasp the concept.

class Example{
  public static void main(String args[])
  {
    int i;
    for( i=0; i<5; i++)
    {
      System.out.println(i + "\n");
      if (i == 3)
        break;
    }
  
  }
}

Output:

0

1

2

3

Hope it was helpful. Thank you.

Give it a read too: Understanding do-while loop in java language

Leave a Reply

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