go to previous page   go to home page   go to next page hear noise highlighting
int[] myWeeklyPay = {769, 588, 1245, 309, 388, 902};
int sum = 0;

for ( int j=0; j<=6; j++ ) sum += myWeeklyPay[j];

Answer:

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

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 );
  }
}      

Java has an enhanced for loop that visits each element of an array in order. It automatically avoids off-by-one bugs. Study the program (above). The program does the same thing as the previous program, but with different syntax.

(There is a colon : separating value and array in the above. This might be hard to see in your browser.)

To read this code out loud say: "For each value in array, ..."

Sometimes the enhanced for loop is called a foreach loop.

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, nor any danger of skipping the first or last element.


QUESTION 14:

Must the enhanced for loop start with the first (index 0) element of the array?


go to previous page   go to home page   go to next page