.


MathBits.com
     Return to Unit Menu | Java Main Page | MathBits.com | Terms of Use                                                                                      
                                                              
 

Ending a Loop or Program Early

Oftentimes it is necessary to end a loop (or a program) earlier than its normal termination.  Below are examples of methods of interrupting or terminating loops and exiting a program.

 

break;

- the break statement gets you out of a loop.  No matter what the loop's ending condition, break immediately says "I'm outta here!"  The program continues with the next statement immediately following the loop.  Break stops only the loop in which it resides.  It does not break out of a "nested loop" (a loop within a loop).

 

continue;

- continue performs a "jump" to the next test condition in a loop.  The test condition is then evaluated as usual, and the loop is executed as long as the test condition remains true.  The continue statement may be used ONLY in iteration statements (loops).  It serves to bypass a portion of the body of the loop within an iteration.

 

Exit method

Sometimes your program can encounter a situation that makes continuing with the program pointless.  In these cases, you can end your program with a call to the exit method   System.exit(0);

if (number = = 0)
{
     System.out.println("Error:  Division by zero.");
     System.exit(0);
}
else
{
     answer = total / number;
     System.out.println("The answer is " + answer);
}

 


                     
 Return to Unit Menu | Java Main Page | MathBits.com | Terms of Use