Solution for Java Lang Index Out of Bounds Exception

Solution for Java Lang Index Out of Bounds Exception

  1. Causes of the java.lang.IndexOutOfBoundsException
  2. Solution for the java.lang.IndexOutOfBoundsException Considering ArrayList
  3. Solution for the java.lang.ArrayIndexOutOfBoundsException Considering Arrays

Today, we will discuss the IndexOutOfBoundsException error considering Arrays and ArrayList. We will also understand the reasons causing this error and, finally, how to solve it.

Causes of the java.lang.IndexOutOfBoundsException

The reasons for having the IndexOutOfBoundsException error are similar in Arrays and ArrayList, except for one difference which is having different error descriptions. We get this error in Arrays and ArrayList as java.lang.ArrayIndexOutOfBoundsException and java.lang.IndexOutOfBoundsException, respectively.

The reasons causing this exception are listed below:

  1. When the ArrayList is empty and try to access the value at the first index, which is 0.
  2. When we try to access an item in an Array or ArrayList at a negative index.
  3. When we try to access an invalid index of an Array or ArrayList, which can be a negative, equal to, or greater than the size of Array or ArrayList.

Remember that the IndexOutOfBoundsException is a run-time exception that is not detected by the Java compiler at compile time. So, it is necessary to know how to access the Array or ArrayList.

The rule of thumb is that the Array or ArrayList must be populated before you access it. Additionally, we can only access the indexes that satisfy this condition: 0 <= index < (Array/ArrayList size).

Let’s learn it with the help of code examples.

Solution for the java.lang.IndexOutOfBoundsException Considering ArrayList

Example Code:

import java.util.ArrayList;

public class TestArrayList{

    public static void main(String[] args){
        ArrayList<String> list = new ArrayList<>();
        //we try to get value at index 0 which is
        //empty right now
        System.out.println(list.get(0));
        list.add("Mehvish"); //saves at index 0
        list.add("Ashiq"); //saves at index 1
   }

}

The above code is causing the IndexOutOfBoundsException error because we are accessing the index 0, which is not populated yet.

To resolve this error, we must first add items in the ArrayList and then access them by ensuring we are not accessing an invalid index. In the following code, we have handled all the situations that can cause IndexOutOfBoundsException.

Example Code:

import java.util.ArrayList;

public class TestArrayList{
    //create array list object of String type
    static ArrayList<String> list = new ArrayList<>();

    //populate array list
    static void populateList(){
        list.add("Mehvish"); //saves at index 0
        list.add("Ashiq"); //saves at index 1
    }
    /*
    Access the index only if the index
    is valid and the list is not empty. Otherwise, print
    the message to inform the user
    */
    static void getElement(int index){
        if(list.size() != 0 && index >= 0 && index < list.size()){
            System.out.println(list.get(index));
        }else{
            System.out.println("The list is empty or you have entered an invalid index");

        }

    }
    //main method
    public static void main(String[] args){
        populateList();
        getElement(0);
    }

}

Let’s test this code on various inputs.

Test 1: User passes 0 to the getElement() function, the output would be,

Mehvish

Test 2: User passes 1 to the getElement() function, the output will look like,

Ashiq

Test 3: User passes 2 to the getElement() function, the output would be,

The list is empty or you have entered an invalid index

Test 4: User passes -1 to the getElement() function, the output is as follows,

The list is empty or you have entered an invalid index

Test 5: The user comments on the populateList() function and passes a valid index. The output will look as follows,

The list is empty or you have entered an invalid index

Solution for the java.lang.ArrayIndexOutOfBoundsException Considering Arrays

Example Code:

public class TestArray{

    public static void main(String[] args)
    {
        int array[] = {1,2,3,4,5} ;
        for (int i = 0; i <= array.length; i++)
            System.out.println(array[i]);
    }

}

This code example causes the ArrayIndexOfBoundsException because of trying to access the index 5, which is invalid. Remember, we can’t access an invalid index.

Let’s test the following code, which has handled all the possible situations and avoided the ArrayIndexOutOfBoundsException error.

Example Code:

import java.util.ArrayList;

public class TestArray{
    //required size of an array
    static int size = 2;
    //declare an int type array of specified size
    static int array[] = new int[size];

    //populate array
    static void populateArray(){
        for (int i = 0; i < size; i++)
            array[i] = i+1;
    }

    //get element if a valid index is passed
    static void getElement(int index){
        if(array.length != 0 && index >= 0 && index < array.length){
            System.out.println(array[index]);
        }else{
           System.out.println("The array is empty or you have entered an invalid index");
        }
    }

    //main method
    public static void main(String[] args){
        populateArray();
        getElement(1);
    }
}

Let’s test this code on different user inputs.

Test 1: User passes 0 to the getElement() function, the output would be,

1

Test 2: User passes 1 to the getElement() function, the output will look like,

2

Test 3: User passes 2 to the getElement() function, the output would be,

The array is empty or you have entered an invalid index

Test 4: User passes -1 to the getElement() function, the output is as follows,

The array is empty or you have entered an invalid index

Test 5: The user comments on the populateArray() function and passes a valid index. The output will look as follows,

0

Why is it 0? It is because we have initialized an empty array where 0 is a default value for the int type. If we do not initialize the elements, then the default values of numeric array elements are set to 0 while the reference elements are set to null.

Mehvish Ashiq avatar Mehvish Ashiq avatar

Mehvish Ashiq is a former Java Programmer and a Data Science enthusiast who leverages her expertise to help others to learn and grow by creating interesting, useful, and reader-friendly content in Computer Programming, Data Science, and Technology.

LinkedIn GitHub Facebook

Related Article - Java Error

  • Class Has Been Compiled by a More Recent Version of Java Runtime
  • GC Overhead Limit Exceeded Error in Java
  • ExceptionInInitializer Error in Java
  • Understanding java.lang.reflect.InvocationTargetException Error in Java
  • Handle Integer Overflow and Underflow in Java
  • The Error: Bad Operand Types for Binary Operator in Java
  • Related Article - Java Exception

  • Java Throwable VS Exception Class
  • Re-Throw Exception in Java
  • Throw New Exception in Java
  • Throw Runtime Exception in Java
  • Java.Lang.ClassNotFoundException: Org.SpringFramework.Web.Servlet.DispatcherServlet
  • Fix Java.Net.SocketException: Broken Pipe Error in Java