You are here

While loops

15 January, 2016 - 09:02
Available under Creative Commons-ShareAlike 4.0 International License. Download for free at

for loops are actually a specialized version of while loops. while loops have no special provisions for

initialization or loop incrementing, just the termination condition.

while loops iterate through the loop body until the termination condition evaluates to a false value.

The following for loop:

for([initialization statement]; [termination expr] ; [increment statement]) { [loop body] } 

Is exactly equivalent to the following:

{ [initialization statement]; while([termination expr]) { [loop body] [increment statement]; } } 

Note the outermost curly braces that create the scoping boundary that encapsulates any variable declared inside the for loop.

The Java compiler will automatically convert a for loop to the above while loop.

Here is the above algorithm that finds a desired value in an array, translated from a for loop to a while loop:

// Find the index of the first occurance of desiredValue in myArray, using a while loop. { idx = -1; // initialize the final result int j = 0; // initialize the index 
while(j < myArray.length) { // loop through the array if(desiredValue == myArray[j]) { // check if found the value idx = j; // save the index break; // exit the loop. } 
j++; // increment the index } } 

Basically, for loops give up some of the flexibility of a while loop in favor of a more compact syntax.

while loops are very useful when the data is not sequentially accessible via some sort of index. Another useful scenario for while loops is when the algorithm is waiting for something to happen or for a value to come into the system from an outside (relatively) source.

do-while loops are the same as while loops except that the conditional statement is evaluated at the end of the loop body, not its beginning as in a for or while loop.

See the Java Resources web site page on loops for more information on processing lists using while loops.