1

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?

2
  • for (int i = 0; i < a.length - 1; i++) Commented Jul 28, 2013 at 7:13
  • this code can throw two ArrayIndexOutOfBoundsException 1) From for loop condition i < a.length while accessing a[i] 2) when condition i < a.length -1 while accessing a[i+1) Commented Jul 28, 2013 at 7:36

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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].

Comments

0

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

Comments

0

You are starting from i=0. So it should be a.length-1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.