Java – Break Statement

When the condition is fulfilled, the break statement in Java is used to exit the programme from the loop containing it.

If the break statement is used in a nested loop (loop inside the loop), the innermost loop will be terminated once the break requirements are met.

Break statement with While loop

If the value of variable j becomes 4, the break statement is used to exit the while loop in the example below.

public class MyClass {
  public static void main(String[] args) {
    int j = 0;
    while (j < 10){
      j++;
      if(j == 4){
        System.out.println("Getting out of the loop.");
        break;
      }
      System.out.println(j); 
    }
  }
}


The output of the above code will be:

1
2
3
Getting out of the loop.

Break statement with For loop

If the value of the variable i become 4, the break statement is used to exit the for a loop.

public class MyClass 
{
    public static void main(String[] args) 
    {
        for (int i = 1; i <= 6; i++)
        {
            if(i == 4)
            { 
                System.out.println("Getting out of the loop.");
                break; 
            }
            System.out.println(i); 
        }
    }
}

The output of the above code will be:

1
2
3
Getting out of the loop.

Break statement with Nested loop

When the condition is met, the Break statement ends the inner loop. In the example below, the inner loop is only terminated when j = 100, causing the programme to bypass the inner loop for j = 100 and 1000.

//Nested loop without break statement
public class MyClass {
  public static void main(String[] args) {
    System.out.println("# Nested loop without break statement");
    for (int i = 1; i <= 3; i++){
      for (int j = 10; j <= 1000; j = j * 10){
        System.out.println(i*j);
      }
    }
  }
}

The output of the above code will be:

# Nested loop without break statement
10
100
1000
20
200
2000
30
300
3000
//Nested loop with break statement
public class MyClass {
  public static void main(String[] args) {
    System.out.println("# Nested loop with break statement");
    for (int i = 1; i <= 3; i++){
      for (int j = 10; j <= 1000; j = j * 10){
        if(j == 100 ){
           break;
        }
        System.out.println(i*j);
      }
    }
  }
}

The output of the above code will be:

# Nested loop with break statement
10
20
30

Click here to open an online compiler.

Next: Java – Label Statement


Leave a Reply

Your email address will not be published.