[Solved] ArrayIndexOutOfBoundException in JAVA


java.lang.ArrayindexOutOfboundsException is Runtime and Unchecked Exception. It’s subclass of java.lang IndexOutOfBoundsException.

ArrayIndexOutOfBoundsException is most common error in Java Program. It throws when an array has been accessed with an illegal index either negative or greater than or equal to the size of the array.

Points To Remember:

  •  Array index starts at zero and goes to length – 1, for example in an integer array int[] counts= new int[20], the first index would be zero and last index out be 19 (20 -1)
  • Array index cannot be negative, hence counts[-1] will throw java.lang.ArrayIndexOutOfBoundsException.
  • The maximum array index can be Integer.MAX_VALUE -1 because array accept data type of index is int and max allowed value for int is Integer.MAX_VALUE.

Constructors:

  • ArrayIndexOutOfBoundsException() : Constructs an  ArrayIndexOutOfBoundsException with no detail message.
  • ArrayIndexOutOfBoundsException(int index) : Constructs a new ArrayIndexOutOfBoundsException class with an argument indicating the illegal index.
  • ArrayIndexOutOfBoundsException(String s) : Constructs an ArrayIndexOutOfBoundsException class with the specified detail message.

Example :

public class ArrayOutOfBoundException {

	public static void main(String[] args) {
		String [] empArr={"Saurabh","Gaurav","Shailesh","Ankur","Ranjith","Ramesh"};
		//No of employee in array
		//Will through IndexOuhtOfBoundException because array having only six element of index 0 to 5
		try
		{
		String name=empArr[8];
		System.out.println("Employee :"+empArr[8]);
		}
		catch(ArrayIndexOutOfBoundsException ex)
		{
			ex.printStackTrace();
		}
	}
}

Output:

java.lang.ArrayIndexOutOfBoundsException: 8
	at example.ArrayIndexOutOfBoundsException.main(ArrayIndexOutOfBoundsException.java:11)<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>
Advertisements

About Saurabh Gupta

My Name is Saurabh Gupta, I have approx. 10 Year of experience in Information Technology World manly in Java/J2EE. During this time I have worked with multiple organization with different client, so many technology, frameworks etc.
This entry was posted in Example, Exception and tagged , , , , , , . Bookmark the permalink.