These classnotes are depreciated. As of 2005, I no longer teach the classes. Notes will remain online for legacy purposes

JAVA01/Loops

Classnotes | JAVA01 | RecentChanges | Preferences

for Loops

In the Java programs you write, you will find many circumstances in which a loop is useful. To creat and control loops, you need to use a loop statement. One loop statement is the "for-loop".

 for (int i = 0; i < 1000; i++ ) {
     // do something here
 }

while Loops

The while loop is useful in situations where you have some specific test that needs to be checked each time there is a loop. Unlike the for loop, you are not incrementing anything, instead you are merely checking for a given condition.

 while (gameLives > 0) {
     // the statements inside the loop go here
 }

Be careful of infinite loops here!

do-while Loops

The while loop is very useful, however, it must check for a pre-existing condition first, and may not even run if the condition is false.

In those situations where you have a loop that needs to go through at least once you can use the "do-while" loop:

 do {
    // perform tasks here
 } while (gameLives > 0);

Exiting a Loop

If you are inside a loop and must exit imediately without finishing the loop, the statement to use is "break".

 while (true) {
   // This is an infinite loop!
   // Oh no! I need to get out of it!
   break;
 }


Classnotes | JAVA01 | RecentChanges | Preferences
This page is read-only | View other revisions
Last edited May 29, 2003 12:48 am (diff)
Search:
(C) Copyright 2003 Samuel Hart
Creative Commons License
This work is licensed under a Creative Commons License.