next up previous
Next: Elimination of break Up: Unit 06 Previous: Flow control statements

Use of the break statement to exit a loop

We have already seen in Unit 5 that the break statement allows us to exit a switch statement. In general, break allows us to exit prematurely from a switch, while, for, or do statement.

Example: Loop to calculate the square root of 10 reals read from input. We want to interrupt the loop as soon as the user inputs a negative value.

double a;
for (int i = 0; i < 10; i++) {
  a = Double.parseDouble(
        JOptionPane.showInputDialog("Input a nonnegative real"));
  if (a >= 0)
    System.out.println(Math.sqrt(a));
  else {
    System.out.println("Error");
    break;
  }
}

Note: In the case of nested loops or of switch statements nested within a loop, the execution of a break causes the exit from a single level of nesting only.


next up previous
Next: Elimination of break Up: Unit 06 Previous: Flow control statements