[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

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s