1.9k views
0 votes
What is the result of the following code?double[] values = new double[4];double sum = 0.0;for (int i = 1; i <= 4; i++) { sum += values[i];}System.out.println(sum);

1 Answer

5 votes

Answer:

The following code as it is results in an array out of bound exception.

Step-by-step explanation:

The reason for this exception is that you tried to access index 4 for an array of length four, because Arrays are indexed from zero, the last element in an array of length 4, will be at index 3 (i.e. 0,1,2,3)

To fix this change for (int i = 1; i <= 4; i++) to for (int i = 0; i < 4; i++).

In this way you code compiles and returns the sum of all elements in the array. Since this array is only created and empty, it outputs 0.0

User Kyesha
by
5.9k points