<< 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.

For-each 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.

Arrays vs. lists

In no particular order...

  • Arrays:
    • Fast access to all elements.
    • Fixed number of elements held.
    • Difficult to insert elements.
    • Can run into problems with uninitialized elements.
    • Minimal safety for out-of-bounds indices.
    • Minimal memory used
    • Simple syntax
    • Must use procedural techniques for processing.
    • Often incompatible with OO architectures.
    • Difficult to prove that processing algorithms are correct.
    • Processing algorithms can be very fast.
    • Processing algorithms can be minimally memory intensive
  • Lists:
    • Slow access except to first element, which is fast.
    • Unlimited number of elements held.
    • Easy to insert elements.
    • Encountering uninitialized elements very rare to impossible.
    • Impossible to make out-of-bounds errors.
    • Not optimized for memory usage.
    • More cumbersome syntax.
    • Can use OO and polymorphic recursive techniques for processing.
    • Very compatible with OO architectures.
    • Easy to prove that processing algorithms are correct.
    • Processing algorithms can be quite fast if tail-recursive and using a tail-call optimizing compiler.
    • Processing algorithms can be very memory intensive unless tail-recursive and using a tail-call optimizing compiler.
Arrays are optimized for size and random access speed at the expense of OO design and recursion. If you do not need speed or low memory, do not use an array. If you must use an array, tightly encapsulate it so that it does not affect the rest of your system.

Get Jobilize Job Search Mobile App in your pocket Now!

Get it on Google Play Download on the App Store Now




Source:  OpenStax, Principles of object-oriented programming. OpenStax CNX. May 10, 2013 Download for free at http://legacy.cnx.org/content/col10213/1.37
Google Play and the Google Play logo are trademarks of Google Inc.

Notification Switch

Would you like to follow the 'Principles of object-oriented programming' conversation and receive update notifications?

Ask