go to previous page   go to home page   go to next page
int[] myWeeklyPay = {769, 588, 1245, 309, 388, 902};
int sum = 0;
for ( int j=0; j<=6; j++ ) sum += myWeeklyPay[j];


The index j goes one cell too far. An ArrayIndexOutOfBoundsException will be thrown and you program will be halted.

Off-by-one errors are very common. A running Java program checks each array index before it is used to be sure it is within bounds.

Enhanced for loop

Java (starting with version 5.0) has an enhanced for loop that visits each element of an array in order. It automatically avoids off-by-one bugs. Here is our program written with an enhanced loop:

class MaxAlgorithm
  public static void main ( String[] args ) 

    int[] array =  { -20, 19, 1, 5, -1, 27, 19, 5 } ;
    int   max;

    // initialize the current maximum
    max = array[0];

    // scan the array
    for ( int value : array )
      if ( value > max )    // examine the current element
        max = value ;         // if it is the largest so far, change max
    System.out.println("The maximum of this array is: " + max );

(There is a colon : separating value and array in the above. This might be hard to see in your browser.) The program does the same thing as the previous program. The enhanced for loop

for ( int value : array )

assigns to value the contents of each cell of the array starting with cell zero and going in order up to the last cell of the array. For each assignment, the loop body is executed. With this enhanced for loop there is no danger of an index that might go out of bounds.

To read this code out loud you say, "For each value in array, ..." Sometimes the enhanced for loop is called a foreach loop.


Must the enhanced for loop start with the first element of the array?