The for...each Loop


There is also a for...each loop, which is used exclusively to loop through elements in an array.

The upper script is the syntax of the for...each loop. The lower script is an example, which outputs all elements in the cars array, using a for...each loop.
 for ( type variable : arrayname ) {
   // code block to be executed
 }

 String[ ] cars = { "Volvo", "BMW", "Ford", "Mazda" };
 for ( String i : cars )
   System.out.print( i );
 // Output: VolvoBMWFordMazda

ForEach.java (printing checkboxes using for...each loop)

 // The checkboxes are handled by Perl.
 // The Java program is only to print the checked checkboxes.
 public class  ForEach {
   public static void  main( String args[ ] ) {
     // Copying one array to another
     String cars[ ] = new String[];
     for ( int i=0; i<; ++i )  cars[i] = args[i];

     // Printing the checked cars
     for ( String car : cars )  System.out.print( car + " " );
     System.out.print( " are picked." );
   }
 }
Volvo   BMW   Ford   Mazda            

Limitations of the for...each loops include:
  • It is not appropriate when you want to modify the array:
for ( int num : marks ) {
  // Only changes num, not the array element.
  num = num*2; 
}

  • It does not keep track of index, so we can not obtain array index by using it:
for ( int num : numbers ) { 
  if ( num == target ) {
    return ???;
    // Do not know the index of num.
  }
}

  • It only iterates forward over the array in single steps:
// Cannot be converted to a for...each loop.
for ( int i=numbers.length-1; i>0; i-- ) {
  System.out.println( numbers[i] );
}

  • It cannot process two decision making statements at once:
// Cannot be easily converted to a for...each. 
for ( int i=0; i<numbers.length; i++ ) {
  if ( numbers[i] == arr[i] ) {
    ...
  }
}




      An apple a day keeps the doctor away.