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

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]);
}

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.

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];
}

In above specific case,

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

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

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

Posted

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *