How To Handle The ArrayIndexOutOfBoundsException in Java?

This Tutorial Provides a Detailed Explanation About an Important Exception thrown by Java Arrays i.e. ArrayIndexOutOfBoundsException with Simple Examples:

We have learned all about Arrays in our previous tutorials. Arrays are static in nature and its dimension or size is determined at the time of their declaration. We also know that this size or the number of elements declared for the array are fixed and are numbered from 0.

Sometimes, the program logic is such that the program tries to access the element from a non-existing index. For example, due to glitches in a program, a program might try to access the 11th element in the array of 10 elements. This results in an abnormal condition.

=> Check Out The Complete Java Training For Beginners

ArrayIndexOutOfBounds Exception in Java

Java provides an exception in the ‘java.lang’ package that is thrown when a non-existing array index is accessed. This is known as the “ArrayIndexOutOfBoundsException”.

ArrayIndexOutOfBoundsException

As already stated, when you try to access array elements beyond a specified length or a negative index, the compiler throws the ‘ArrayIndexOutOfBoundsException'.

ArrayIndexOutOfBoundsException implements a ‘serializable’ interface and derives from the ‘indexOutOfBoundsException’ which in turn is derived from the RuntimeException class which is a subclass of the ‘exception’ class. All these classes belong to the ‘java.lang’ package.

ArrayIndexOutOfBoundsException is a runtime, unchecked exception and thus need not be explicitly called from a method. Following is the class diagram of ArrayIndexOutOfBoundsException that shows the inheritance hierarchy as well as the constructors for this exception.

Class Diagram Of ArrayIndexOutOfBoundsException

Class diagram of ArrayIndexOutOfBoundsException

As explained earlier, the ArrayIndexOutOfBoundsException class has three superclasses i.e. java.lang.exception, java.lang. runtimeException and java.lang.indexOutOfBoundsException.

Next, we will see some examples of ArrayIndexOutOfBoundsException in java.

Example Of ArrayIndexOutOfBounds Exception

Let's see the first example that shows the ArrayIndexOutOfBounds Exception being thrown.

class Main {  
    public static void main(String[] args) {  
        //array of subjects. There are 5 elements.
        String[] subjects = {"Maths","Science","French","Sanskrit", "English"};   

        //for loop iterates from 0 to 5 (length of array)  
        for(int i=0;i<=subjects.length;i++) {       
            //when ‘i’ reaches 5, it becomes invalid index and exception will be thrown
            System.out.print(subjects[i] + " ");      
        }  
    } 

Output:

Example of ArrayIndexOutOfBounds Exception

In the above program, we have array subjects consisting of 5 elements. However, in the for loop, we have set the iteration condition as i<=subjects.length. Thus for the last iteration, the value of i is 5 which exceeds the array size. Hence, when printing array elements, the iteration i=5, results in ArrayIndexOutOfBoundsException being thrown.

Given below is another example of accessing the negative index.

class Main {  
    public static void main(String[] args) {  
        //array of integers
        Integer[] intArray = {10,20,30,40,50};   
        //index = 0; accessing element is successful
        System.out.println("First element: " + intArray[0]);
        //index = -4; accessing fails. Exception thrown
        System.out.println("Last element: " + intArray[-4]);
    }  

Output:

Example of accessing the negative index

In the above program, we declare an array of type integer and then access the elements using individual indices. The first expression is valid but in the second expression, we have attempted to access the element at index = -4. Hence the second expression throws ArrayIndexOutOfBoundsException as shown in the output.

Avoiding ArrayIndexOutOfBoundsException

The common cause for the occurrence of ArrayIndexOutOfBoundsException is that the programmer makes a mistake in using the array indices.

Thus the programmer can follow the below techniques to avoid the occurrence of ArrayIndexOutOfBoundsException.

Use Proper Start And End Indices

Arrays always start with index 0 and not 1. Similarly, the last element in the array can be accessed using the index ‘arraylength-1’ and not ‘arraylength’. Programmers should be careful while using the array limits and thus avoid ArrayIndexOutOfBoundsException.

Using Enhanced For Loop

An enhanced for loop or for-each loop iterates over contiguous memory locations like arrays and only accesses the legal indices. Hence when enhanced for loop is used, we need not worry about wrong or illegal indices being accessed.

Example of iterating over an array using Enhanced for Loop.

class Main {  
   public static void main(String[] args) {  
         //array of subjects. There are 5 elements.
         String[] subjects = {"Maths","Science","French","Sanskrit", "English"};   

         System.out.println("")
        //define enhanced for loop to iterate over array 
        for(String strval:subjects) {       
            //iterates only through valid indices
            System.out.print(strval + " ");      
        }  
    } 
}

Output:

Example of iterating over an array using enhanced for loop

We have used an enhanced for loop in the above program to iterate over the array of subjects. Note that for this loop, we need not specify the index explicitly. Hence the loop iterates over the array till the end of the array are reached.

Thus it is easy to fix the ArrayOutOfBoundsException by using proper indices and taking care when specifying the array limits. We can also make use of enhanced for loop to iterate over the arrays.

Let's move on to answer a few frequently asked questions regarding exceptions in arrays.

Frequently Asked Questions

Q #1) Why does ArrayIndexOutOfBoundsException occur?

Answer: ArrayIndexOutOfBoundsException occurs when you try to access an array index that is non-existingi.e. the index is either negative or out of bounds with the array limits.

Q #2) What is NegativeArraySizeException?

Answer: NegativeArraySizeException is a runtime exception that is thrown if an array is defined with a negative size.

Q #3) What is array out of bound exception?

Answer: An array out of bound exception occurs when a program tries to access an array element by specifying a negative index or an index that is not in the range of the specified array.

Q #4) Can we throw NullPointerException in Java?

Answer: Yes, you can throw NullPointerException in Java or else the JVM will do it for you.

Q #5) Is NullPointerException checked or unchecked?

Answer: NullPointerException is unchecked and extends RuntimeException. It does not compel the programmer to use the catch block to handle it.

Conclusion

In this tutorial, we discussed the details of ArrayIndexOutOfBoundsException in Java. This exception is usually thrown when in a program we try to access the array elements using the negative index or out of bounds index like specifying an index that is greater than the specified array length.

This exception can be avoided by taking care of indices while accessing the arrays or using enhanced for loop which by design accesses only legal indices.

We will move on to other array topics in our subsequent tutorials.

=> Explore The FREE Java Course Here.