-5

I'm adding two arrays of the same length and I've written the code for it and no compile error shows up but when I run it I get:

java.lang.ArrayIndexOutOfBoundsException: 5

public class sumArray {
    static double[] data1= {1.2, 2.3, 3.4, 5.1, 7.8};
    static double[] data2= {5.3, 7.9, 2.1, 6.4, 9.2};
    public static void main(String[] args){
        sumArray();  
    }

    public static double [] sumArray(){
        double[] data3 = new double[data1.length];
        for(int i = 0; i <= data1.length; i++){
            data3[i] = data1[i] + data2[i];
        }
        return data3;
    }
}
Andrii Abramov
  • 10,019
  • 9
  • 74
  • 96
user3705481
  • 5
  • 1
  • 1
  • 2

5 Answers5

3

You're comparing from 0 - 5 (i.e. 6 elements, but your array has only 5), so you're going out of the bounds.

All you have to do is to go from 0 - data1.length - 1 like:

Change

for (int i = 0; i <= data1.length; i++){
     data3[i] = data1[i] + data2[i];

}

to

for (int i = 0; i < data1.length; i++){
     data3[i] = data1[i] + data2[i];
}

or change it to:

for (int i = 0; i <= (data1.length - 1); i++){
     data3[i] = data1[i] + data2[i];

}
Andrii Abramov
  • 10,019
  • 9
  • 74
  • 96
Frakcool
  • 10,915
  • 9
  • 50
  • 89
1

You are going off the end of the array. Change this line to:

for(int i = 0; i < data1.length; i++){

data1.length is the size of the array. An array of size 5 has indexes from 0 - 4. So you should not let i become greater than 4.

Andrii Abramov
  • 10,019
  • 9
  • 74
  • 96
Edwin Torres
  • 2,774
  • 1
  • 13
  • 15
1

In your for loop your counting variable can reach 5.

for (int i = 0; i <= data1.length; i++){
     data3[i] = data1[i] + data2[i];
}

This is because you say you want to go on as long as i is equal to or smaller than data1.length.

Thus because you have the = sign in your expression it will reach 5 and that throws an error because there's only data at the positions 0 1 2 3 and 4.

Therefore your code should be:

for(int i = 0; i < data1.length; i++){
     data3[i] = data1[i] + data2[i];
}

Hope this explains it.

Roan
  • 1,200
  • 2
  • 19
  • 32
0
Array always start from zero position,
now just look at your code,data1 and data2 size is 5(i.e. data1[5],data2[5]) means it start from 
data1[0]=1.2,data[1]=2.3,data[2]=3.4,data[3]=5.1,data[4]=7.8
same logic for data2
now check your for loop which says that 
for(int i=0,i<=5,i++) means this loop get execute 6 times
i.e. data[0],data[1],data[2],data[3],data[4],data[5]
hope so you got it why it's throwing ArrayIndexOutOfBoundsException for 5th position
Abhishek Mishra
  • 611
  • 4
  • 11
0

The position of the last element in an array is = the number of elements in the array or the length of the array -1. Therefore the condition i <= data1.length must be changed to : i < data1.length.