Categories
arrayindexoutofboundsexception arrays exception java

What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?

346

What does ArrayIndexOutOfBoundsException mean and how do I get rid of it?

Here is a code sample that triggers the exception:

String[] names = { "tom", "bob", "harry" };
for (int i = 0; i <= names.length; i++) {
    System.out.println(names[i]);
}

5

  • 1

    In reference to the last question, code would be helpful. Are you accessing the array with a known index, or do you have to start debugging to figure out how the index is calculated when the error occurs?

    – justkt

    Apr 5, 2011 at 15:57

  • 48

    Replace i <= name.length with i < name.length – or better, write an enhanced for loop. (for (String aName : name) { ... })

    Apr 5, 2011 at 16:14

  • 2

    it means, that you want to get element of array that not exist, ‘i<=name.length’ means that you want to get element length+1 – its not exist.

    – hbk

    Feb 22, 2013 at 17:50

  • 1

  • The array goes out of bounds when the index you try to manipulate is more than the length of the array. For correctness, your indices should always be one less than the total no. of array elements because the array index starts from 0 and not 1.

    Mar 26, 2020 at 4:40

329

Your first port of call should be the documentation which explains it reasonably clearly:

Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.

So for example:

int[] array = new int[5];
int boom = array[10]; // Throws the exception

As for how to avoid it… um, don’t do that. Be careful with your array indexes.

One problem people sometimes run into is thinking that arrays are 1-indexed, e.g.

int[] array = new int[5];
// ... populate the array here ...
for (int index = 1; index <= array.length; index++)
{
    System.out.println(array[index]);
}

That will miss out the first element (index 0) and throw an exception when index is 5. The valid indexes here are 0-4 inclusive. The correct, idiomatic for statement here would be:

for (int index = 0; index < array.length; index++)

(That’s assuming you need the index, of course. If you can use the enhanced for loop instead, do so.)

5

  • 4

    I’d add that for multidimensional arrays that might have an arbitrary shape in Java, the nested loops should check for the relevant subarray length: for (int nestedIndex = 0; nestedIndex < array[outerIndex].length; nestedIndex++) { ... array[outerIndex][nestedIndex] ... }.

    – Andrey

    Mar 2, 2017 at 22:04

  • It would be could to mention in the answer that the stack trace should be consulted to find the exact line where the error occurs. IMO, this is the first port of call.

    – rghome

    Dec 8, 2021 at 7:49

  • @rghome: That’s not an answer to “What does ArrayIndexOutOfBoundsException mean” though. I think before trying to understand what in your code causes it, you need to understand what it means. If I tell you that you’ve got a GrobulatorError in a given line of code, how would you expect to identify what’s causing it if you have no idea what a GrobulatorError is?

    – Jon Skeet

    Dec 8, 2021 at 7:58


  • Yes – but. We get a lot of these and there is a need to find a link for the close-as-duplicate. Often the OP hasn’t even identified the line of code it happened on. There is another question on how to analyse a stack trace, but I am thinking it would be good to have a single procedure for finding the IOOB, so that someone can close the question confident that the OP can then solve it for themselves with the link.

    – rghome

    Dec 8, 2021 at 8:39

  • @rghome: A canonical question and answer sounds fine, but I don’t think this is necessarily the right one. Or even if it is the right one, I’d still say the first thing to do is understand what the error means, before looking in your code to see why it happens.

    – Jon Skeet

    Dec 8, 2021 at 8:42

57

if (index < 0 || index >= array.length) {
    // Don't use this index. This is out of bounds (borders, limits, whatever).
} else {
    // Yes, you can safely use this index. The index is present in the array.
    Object element = array[index];
}

See also:


Update: as per your code snippet,

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

The index is inclusive the array’s length. This is out of bounds. You need to replace <= by <.

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

    26

    From this excellent article: ArrayIndexOutOfBoundsException in for loop

    To put it briefly:

    In the last iteration of

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

    i will equal name.length which is an illegal index, since array indices are zero-based.

    Your code should read

    for (int i = 0; i < name.length; i++) 
                      ^