Beginner's nightmare

exercise No. 207

Q:

We consider the following class method sum:

01 /**
02  * Summing up an int array's values
03  *
04  * @param values An array of int values
05  * @return The sum of all array values
06  */
07 public static int sum(int[] values) {
08
09    int sum;
10
11    for (i = 0; i <= values.length; i++) {
12        sum += values[i];
13    }
14    return sum;
15 }

This code does contain errors. Explain and correct each of those. Line numbers are being provided for your convenience

A:

There are errors:

Erroneous code Correct code
/**
 * Summing up an int array's values
 *
 * @param values An array of int values
 * @return The sum of all array values
 */
public static int sum(int[] values) {

   int sum; 

   for ( i = 0; i <= values.length; i++) {
        sum += values[i];
   }
   return sum;
}
/**
 * Summing up an int array's values
 *
 * @param values An array of int values
 * @return The sum of all array values
 */
public static int sum(int[] values) {

   int sum = 0;

   for (int i = 0; i < values.length; i++) {
        sum += values[i];
   }
   return sum;
}

Missing initialization sum = 0.

Missing type i.e. int i.

Off by one error: Last array index being values.length - 1 requires i < values.length avoiding an ArrayIndexOutOfBoundsException.