Arrayindexoutofboundsexception in java

As you know Array has a fixed length. You can’t change it after the declaration of the array. It consists of a fixed number of elements. You can access the element from an array by using the index. The index of an array is always an integer value and it starts from 0 and ends with array’s length-1. If users trying to access an element by either negative or greater than or equal to the size of the array then the system will throw an exception called ArrayIndexOutOfBoundsException. It is a run time exception. In this article, we will discuss all the scenarios of arrayindexoutofboundsexception in java or java arrayindexoutofboundsexception.

class ArrayIndexOutOfBoundsExceptionExample 
{
   public static void main(String[] args)
   {
      String[] names = { "Ravi", "Rama", "Radhe"};
      for (int i = 0; i <= 3; i++) 
     	System.out.println("Names of Students = "+names[i]);
   }
}

Output: Names of Students = Ravi
Names of Students = Rama
Names of Students = Radhe Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 3 at ArrayIndexOutOfBoundsExceptionExample.main(ArrayIndexOutOfBoundsExceptionExample.java:6)

Explanation:
In this example compiler simply prints the names of the student until i(index) is less than 3. Complier throwing an exception when i(index) becomes equal to 3 because we are trying to get element by index(i) which is equal to the size of the array. We should always remember one thing the index of an array starts from 0 and you can traverse an array’s length – 1. As you can see in the below image. The name at index 3 (i = 3) doesn’t exists.

Arrayindexoutofboundsexception in java

1. Quiz, Read the below code and do answer.

If an index value is less than 0 or greater than or equal to length of array.

Click on anyone to know the answer.

2 thoughts on “Arrayindexoutofboundsexception in java”

Leave a Comment