Java break Statement

The break statement in Java immediately ends the loop, and the program's control shifts to the statement that follows the loop.

Syntax

break;

Example

class Main {
  public static void main(String[] args) {
      
    // create an array with initial values.
    int[] numbers = {1,3,4,5,7,8};
    
    // for-each loop to print each numbers.
    for (int number: numbers) {
      if(number==5){
          break;
      }
      else{
          System.out.println(number);
      }
    }
  }
}

Output

1
3
4
End of program.

In the above program, we have initialize an integer array and loop through it using for-each loop.

Inside the for-each block of code we check whether the value is 5 . If the value is 5 then it will break from the for-each loop else it will print the value in the console.

The break statement will be used in switch statement also to break for the block of code from further checking of condition.


Most Read