Enhanced for Loop

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page        

Answer:

Yes.

Enhanced for Loop

The enhanced for loop (sometimes called a "for each" loop) can be used with any class that implements the Iterable interface, such as ArrayLists. Here is the previous program, now written using an enhanced for loop.

import java.util.* ;
class IteratorExampleTwo
{
  public static void main ( String[] args)
  {
    ArrayList names = new ArrayList();

    names.add( "Amy" );    names.add( "Bob" ); 
    names.add( "Chris" );  names.add( "Deb" ); 
    names.add( "Elaine" ); names.add( "Frank" );
    names.add( "Gail" );   names.add( "Hal" );

    for ( String name : names ) 
      System.out.println( name );

  }
}

The program does the same thing as the previous program. The enhanced for loop

    for ( String name : names )
      System.out.println( name );

accesses the objects in the ArrayList and assigns their references to name. With an enhanced for loop there is no danger of an index that might go out of bounds. (There is a colon : separating name and names in the above. This might be hard to see in your browser.)

QUESTION 18:

Can primitive types, like int and double be added to an ArrayList ?