Additional Loop Control: break and continue

Contact Us or call 1-877-932-8228
Additional Loop Control: break and continue

Additional Loop Control: break and continue

Breaking Out of a Loop

The break statement will end a loop early and execution jumps to the first statement following the loop. The following example prints random digits until a random value is less than 0.1.

Code Sample:

Java-Control/Demos/Break.java
public class Break {
  public static void main(String[] args) {
    for ( ; ; ) { // creates an infinite loop
                  // no initialization, no test, no increment
      double x = Math.random();
      if (x < 0.1) break;
      System.out.print((int) (x * 10) + " ");
    }
    System.out.println("Done!");
  }
}

This code loops, generating and printing a random number for each iteration. If the number is less than 0.1, we break out before printing it.

Code Sample:

Java-Control/Demos/BreakNot.java
public class BreakNot {
  public static void main(String[] args) {
    double x = 0.0;
    for ( x = Math.random(); x >= 0.1; x = Math.random() ) {
      System.out.print((int) (x * 10) + " ");
    }
    System.out.println("Done!");
  }
}

This code avoids the break, by creating and testing the random number in the control part of the loop. As part of the iteration condition, if the number is less than 0.1, the loop simply ends "normally".

Next