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:
 for ( int i = 0; i < 10; i++ ) {
   if ( i == 4 )  break;
   System.out.print( i );
 }    // 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)
// Using break to exit a loop 
class BreakLoop { 
  public static void main( String args[ ] ) { 
    // Initially loop is set to run from 0-9.
    for ( int i = 0; i < 10; i++ ) { 
      // Terminate loop when i is args[0]. 
      if ( i == Integer.parseInt( args[0] ) )
        break; 
      System.out.print( i + " " ); 
    } 
    System.out.print( "Over" ); 
  } 
}
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.
label: {
  statement1;
  statement2;
  statement3;
     .
     .
}
BreakLabel.java (the break statement)
// Using break with goto
class BreakLabel { 
  public static void main( String args[ ] ) { 
    boolean t = Boolean.parseBoolean( args[0] ); 
    first: { 
      second: { 
        third: { 
          // Before break 
          System.out.println( "Before the break" ); 
          // break will take the control out of second block. 
          if ( t )  break second; 
          System.out.println( "Won't execute if true." ); 
        }  // End of third block
        System.out.print( "Won't execute if true." ); 
      }  // End of second block
      System.out.println( "After second block" ); 
    }  // End of first block
  } 
}
shell> java BreakLabel          



      “Learn to light a candle in the darkest moments of someone’s life.    
      Be the light that helps others see;    
      it is what gives life its deepest significance.”    
      ― Roy T. Bennett, The Light in the Heart