Facebook Page Twitter Page LinkedIn Page
× Java Tutorial Java Advanced Java Resources


The Java break keyword is used to terminate the program out of the loop containing it. If the break statement is used in a nested loop (loop inside loop), it will terminate innermost loop.

Break statement with While loop

public class MyClass {
  public static void main(String[] args) {
    int i = 6;
    int j = 0;
    while (j < i){
        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

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

The Break statement terminates the inner loop whenever condition is fulfilled. In below mentioned example, program terminates the inner loop only when j = 100 (resulting the program to skip the inner loop for j = 100 and 1000).

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

//Nested loop with break statement

public class MyClass {
  public static void main(String[] args) {
    
    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:

# output of nested loop without break statement
10
100
1000
20
200
2000
30
300
3000

# output of nested loop with break statement
10
20
30

❮ Java Keywords