Java – ArrayIndexOutOfBoundsException

Previous
Next

ArrayIndexOutOfBoundsException occurs when we try to access array elements which are out of bounds.

class Demo 
{
	static int arr[ ] = new int[5] ;
	public static void main(String[] args) 
	{
		System.out.println("arr[0] value : " + arr[0]);  
		System.out.println("arr[arr.length-1] value : " + arr[arr.length-1]);  
		System.out.println("arr[arr.length] value : " + arr[arr.length]);   // ArrayIndexOutOfBoundsException
	}
}
  • Often we try to access element beyond the size of the array.
  • for example, if we have a size 10 arrays and if we try to access the 11thelement then ArrayIndexOutOfBoundsException will be thrown by the compiler.
  • Let’s look at the software below for an example.
public class Demo {
	publicstaticvoid main(String[] args) {

		int[] a1 = newint[2];
		a1[0] = 1;
		a1[1] = 2;
		System.out.println(a1[2]);
	}
}
Previous
Next

Add Comment

Courses Enquiry Form