Reputation: 107
I have this code to swap pairs of array elements:
int[] a= new int[]{1,2,3,4};
for(int i=0; i<a.length ;i++)
{
int temp= a[i];
a[i] = a[i+1];
a[i+1] = temp;
}
However, I am getting the following exception:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
at com.B.main(B.java:14)
Why am I getting this exception? How can I fix it?
Upvotes: 1
Views: 239
Reputation: 4033
The error is due to the reason that you are accessing the element at a.length
which is not available, so the code throws ArrayIndexOutOfBoundsException
so please use a.length - 1
in the for loop. The problem in your case was at last iteration. You were trying to use a[4], but the elements in array a[ ] started from a[0] and ended at a[3].
Upvotes: 1
Reputation: 95958
Lets draw a table:
i | a[i]
---+------
0 | 1 :)
1 | 2 :)
2 | 3 :)
3 | 4 :)
4 | ? :_(
Note that arrays are zero-based in Java, that means, if you have an array of size N
(4 in your case), then the indexes are from 0
to N - 1
(0
to 3
in your case).
So when you try to access a[a.length - 1 + 1]
(a[i+1]
in the last iteration) you're getting ArrayIndexOutOfBoundsException.
Upvotes: 4
Reputation: 240870
You are going upto a.length - 1
for(int i=0; i<a.length ;i++)
and you are trying to access element at a.length
which is out of bound
Upvotes: 0