The break Statement


Java supports three jump statement: break, continue, and return. These three statements transfer control to other part of the program. The break statement can be used to “jump out” of a loop statement.

This example jumps out of the loop when i is equal to 4. In Java, break is majorly used for:
1for ( int i = 0; i < 10; i++ ) {
2  if ( i == 4 break;
3  System.out.print( i );
4}    // Output: 0123
  • Using break to exit a loop: Using break, we can force immediate termination of a loop, bypassing the conditional expression and any remaining code in the body of the loop.

BreakLoop.java (breaking a loop)
01// Using break to exit a loop
02class BreakLoop {
03  public static void main( String args[ ] ) {
04    // Initially loop is set to run from 0-9.
05    for ( int i = 0; i < 10; i++ ) {
06      // Terminate loop when i is args[0].
07      if ( i == Integer.parseInt( args[0] ) )
08        break;
09      System.out.print( i + " " );
10    }
11    System.out.print( "Over" );
12  }
13}
shell> java BreakLoop  

      Output:
  • Using break as a form of goto: Java does not have a goto statement. Instead, Java uses label, which is used to identify a block of code. Break statement can be use to jump out of target block, but you cannot break to any label which is not defined in an enclosing block.
1label: {
2  statement1;
3  statement2;
4  statement3;
5     .
6     .
7}
BreakLabel.java (the break statement)
01// Using break with goto
02class BreakLabel {
03  public static void main( String args[ ] ) {
04    boolean t = Boolean.parseBoolean( args[0] );
05    first: {
06      second: {
07        third: {
08          // Before break
09          System.out.println( "Before the break" );
10          // break will take the control out of second block.
11          if ( t )  break second;
12          System.out.println( "Won't execute if true." );
13        // End of third block
14        System.out.print( "Won't execute if true." );
15      // End of second block
16      System.out.println( "After second block" );
17    // End of first block
18  }
19}
shell> java BreakLabel