Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]); } 
like image 544
Aaron Avatar asked Apr 05 '11 15:04

Aaron


People also ask

What is Java Lang ArrayIndexOutOfBoundsException?

java.lang.ArrayIndexOutOfBoundsException. 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.

How do you avoid an out of bound exception?

To avoid the ArrayIndexOutOfBoundsException , the following should be kept in mind: The bounds of an array should be checked before accessing its elements. An array in Java starts at index 0 and ends at index length - 1 , so accessing elements that fall outside this range will throw an ArrayIndexOutOfBoundsException .

What type of error is ArrayIndexOutOfBoundsException?

The ArrayIndexOutOfBoundsException is a Runtime Exception thrown only at runtime. The Java Compiler does not check for this error during the compilation of a program.


2 Answers

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

like image 55
Jon Skeet Avatar answered Oct 05 '22 09:10

Jon Skeet


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:

  • The Java Tutorials - Language Basics - Arrays

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++) { 
like image 41
BalusC Avatar answered Oct 05 '22 07:10

BalusC