ArrayIndexOutOfBoundsException in Java




ArrayIndexOutOfBoundsException occurs when you try to access an array element which is out of the range of index of that array.

e.g. int[] numbers = new int[20];

numbers[13] = 123; //Valid

numbers[0] = 3673; //Valid

numbers[19] = 1823; //Valid

numbers[-3] = 1263; //InValid. It Will give ArrayIndexOutOfBoundsException.

numbers[20] = 4123; //InValid. It Will give ArrayIndexOutOfBoundsException.

numbers[25] = 45123; //InValid.It Will give ArrayIndexOutOfBoundsException.

For int[] numbers = new int[20]; , the valid range of index is from 0 to 19.

Index always starts from 0 till (arraylength-1).

ArrayIndexOutOfBoundsException is Checked or Unchecked Exception??

ArrayIndexOutOfBoundsException is a subclass of RuntimeException. RuntimeException is an unchecked exception. Hence, All subclasses of RuntimeException will also be unchecked exception.

So, ArrayIndexOutOfBoundsException is an Unchecked Exception.

Demo Program : ArrayIndexOutOfBoundsException

package com.masterjavatutorial;
public class TestExample {
	public static void main(String[] args) {
		int numbers[] = new int[20];
		numbers[13] = 123; //Valid

		numbers[0] = 3673; //Valid

		numbers[19] = 1823; //Valid

		numbers[20] = 4123; //InValid. It Will give ArrayIndexOutOfBoundsException.

	}
}

Output of the above program is as below:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 20
	at com.masterjavatutorial.TestExample.main(TestExample.java:11)

It is clear from the above program output as 20 is out if range of index of the given array and hence it gives this exception.