<< Chapter < Page | Chapter >> Page > |
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 indexwhile(j<myArray.length) { // loop through the array
if(desiredValue == myArray[j]) { // check if found the value
idx = j; // save the indexbreak; // 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.
An exceedingly common
for
-loop to write is the following;
Stuff[] s_array = new Stuff[n];
// fill s_array with valuesfor(int i = 0; i<s_array.length; i++) {
// do something with s_array[i]}
Essentially, the loop does some invariant processing on every element of the array.
To make life easier, Java implements the
for-each loop , which is just an alternate
for
loop syntax:
Stuff[] s_array = new Stuff[n];
// fill s_array with valuesfor(Stuff s:s_array) {
// do something with s}
Simpler, eh?
It turns out that the for-each loop is not simply relegated to array. Any class that implements the
Iterable
interface will work. This is discussed in another module, as it involves the use of generics.
In no particular order...
Notification Switch
Would you like to follow the 'Principles of object-oriented programming' conversation and receive update notifications?