Skip to main content
Lesson 9 - while Loops
Lesson MenuPreviousNext
  
The break Statement Variations page 5 of 9

  1. Java provides a break command that forces an immediate end to a control structure (while, for, do, and switch).

  2. The same problem of keeping a running total of integers provides an example of using the break statement:

    ConsoleIO console = new ConsoleIO();
    total = 0;
    number = 1;	/* set to an arbitrary value */
    
    while (number >= 0)
    {
      System.out.print( "Enter a number (-1 to quit) --> ");
      number = console.getInt();
    
      if (number < 0)
        break;
    
      total += number;  // this does not get executed if number < 0
    }
    1. As long as (number >= 0), the break statement will not occur and number is added to total.
    2. When a negative number is typed in, the break statement will cause program control to immediately exit the while loop.

  3. The keyword break causes program control to exit out of a while loop. This contradicts the rule of structured programming that states that a control structure should have only one entrance and one exit point.

  4. The switch structure (to be covered in a later lesson) will require the use of the break statement.


Lesson MenuPreviousNext
Contact
 ©ICT 2003, All Rights Reserved.