java.lang.ArrayIndexOutOfBoundsException

One of the feature in the Java programming language is usage of arrays. The advantage of using arrays is to store the large number of values and retrieve them using the index values. Each array is treated as an object itself. Each array has the fixed number of elements and it will not be changed once the size is allocated. One of the common issue encountered by Java programmers is ArrayIndexOutOfBoundsException. If you are trying to access an element in the array by using the index which is outside the range or capacity of that array.

Look at the below example:


public class ArrayBoundExceptionExample {
	public static void main(String[] args) {
		String s[] = {"STR1","STR2","STR3"};
		System.out.println(s[4]);
	}
}

If you run the above example, you will get get the below exception:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
	at ArrayBoundExceptionExample.main(ArrayBoundExceptionExample.java:5)

The exception says thet application trying to access the index “4″ which is not in the range. The actual indexes are o,1,2 for the array “s[]“. Hence the application throws the java.lang.ArrayIndexOutOfBoundsException.

Look at the below example which has the negative index:

public class ArrayBoundExceptionExample {
	public static void main(String[] args) {
		String s[] = {"STR1","STR2","STR3"};
		System.out.println(s[-2]);
	}
}

The exception thrown is:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -2
	at ArrayBoundExceptionExample.main(ArrayBoundExceptionExample.java:5)

If you pass index value greater than or equal to the size of array or the negative value, then java.lang.ArrayIndexOutOfBoundsException will be thrown.

This exception also thrown when using the List or any other collection objects. Look at the below example.

import java.util.ArrayList;

public class ArrayBoundExceptionExample {
	public static void main(String[] args) {
		ArrayList<String> s = new ArrayList<String>();
		s.add("STR1");
		s.add("STR2");
		s.add("STR3");
		System.out.println(s.get(4));
	}
}

The exception thrown will be:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 4, Size: 3
	at java.util.ArrayList.RangeCheck(Unknown Source)
	at java.util.ArrayList.get(Unknown Source)
	at ArrayBoundExceptionExample.main(ArrayBoundExceptionExample.java:10)

To avoid this exception, it is good practice to ensure that the application not accessing the index which outside the range. Add suitable conditions to check the index ranges.

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*