I am getting an Array Index Out Of Bounds Exception ?

Modified on Tue, 28 Mar, 2023 at 4:39 PM

Do you understand the error?

As the name says, we have an index that tries to access an element in an array that does not exist.

Where is the error occurring?

Can you check the places you’re trying to access the array? This could be anywhere in the code, if you have a loop or recursive calls where the array is being indexed, check them as well. 

Why do you think you are seeing this error? What might be causing it?

If in any case your index goes out of range of 0 to n-1, where n is the length of the array you would get the exception saying the index is out of bounds.

How to Debug this? To debug this issue, I would recommend the following steps:

Dry run with an example and check what array values you’re trying to index.

The error code would look like this:

arr = {1, 2, 3}

val = arr[3]

Here the array only has values from index 0 to 2 but we’re trying to access the array with index 3. This would give you an error. To fix this, you would need to analyze why your code is trying to access an index that it shouldn’t. This could be happening in a loop, you would need to check the loop conditions and see that they are within expected range.

As an example:

for(i=0; i <= arr.length; i++) //gives error as i goes from 0 -> 3

for(i=0; i < arr.length; i++) //does not give error as i goes from 0 -> 2  //Approved

Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select at least one of the reasons
CAPTCHA verification is required.

Feedback sent

We appreciate your effort and will try to fix the article