How to break out of the loop in Java?

In this Java tutorial, you will learn how to break out of the loop in Java, including the nested loop. We’ll use a for-loop, but we can use the same approach with while and do-while loops.

Check out the Java How-To tutorials page to find more Java example programs. 

Break out of the loop in Java

When we work with the loops, we often want to break out and stop execution when a certain condition is met. We can do that using the break keyword.

Let’s first see how we can break out of the single loop.

Example

class BreakOutOfLoop {

  public static void main(String[] args) {

    int[] arr = {1, 2, 3, 4, 5};

    // iterate over array
    for (int i = 0; i < arr.length; i++) {

      if (arr[i] == 3) { // break out of the loop if the current value is equals to 3
        System.out.println("Breaking out of the loop!");
        break;
      } else {
        System.out.println("Current value: " + arr[i]);
      }
    }

  }
}
Current value: 1 Current value: 2 Breaking out of the loop!

Break out of a nested loop

When we have a loop inside another, that is called a nested loop. If we want to break out of the nested loop we first need to label both loops, so that JVM can know from which loop we want to exit.

Example

class BreakOutOfNestedLoop {

  public static void main(String[] args) {

    int[] arr1 = {1, 2, 3, 4, 5};

    int[] arr2 = {6, 7, 8, 9, 10};

    // enhanced for-loops
    outer: for (int k : arr1) {
      inner: for (int i : arr2) { // nested for-loop
        if (k + i == 12) {
          break inner;
        }
      }
      
    }
  }

}


Here, we added labels for the outer and inner loop, and we used the label of the inner loop together with the break keyword to exit from it when the condition inside the if-else statement is met.

Note: There is no need to add a label for the outer loop, but it is a good practice.

Leave a Reply

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