Need Complete Explanation? Read this
The index of an Array always starts from 0. Therefore as you are having 64 elements in your array then their indexes will be from 0 to 63. If you want to access the 64th element then you will have to do it by a[63].
Now if we look at your code, then you have written your condition to be for(int i=1;i<=a.length;i++) here a.length will return you the actual length of the array which is 64.
Two things are happening here:
- As you start the index from 1 i.e.
i=1 therefore you are skipping the very first element of your array which will be at the 0th index.
- In the last it is trying to access the
a[64] element which will come out to be the 65th element of the array. But your array contains only 64 elements. Thus you get ArrayIndexOutOfBoundsException.
The correct way to iterate an array with for loop would be:
for(int i=0;i < a.length;i++)
The index starting from 0 and going to < array.length.