How to Fix Java Error java.lang.ArrayIndexOutOfBoundsException

Posted by Marta on March 4, 2022 Viewed 8005 times

Card image cap

In this article, you will learn the main reason why you will face the java.lang.ArrayIndexOutOfBoundsException Exception in Java along with a few different examples and how to fix it.

I think it is essential to understand why this error occurs, since the better you understand the error, the better your ability to avoid it.

This tutorial contains some code examples and possible ways to fix the error.

Watch the tutorial on Youtube:

What causes a java.lang.ArrayIndexOutOfBoundsException?

The java.lang.ArrayIndexOutOfBoundsException error occurs when you are attempting to access by index an item in indexed collection, like a List or an Array. You will this error, when the index you are using to access doesn’t exist, hence the “Out of Bounds” message.

To put it in simple words, if you have a collection with four elements, for example, and you try to access element number 7, you will get java.lang.ArrayIndexOutOfBoundsException error.

To help you visualise this problem, you can think of arrays and index as a set of boxes with label, where every label is a number. Note that you will start counting from 0.

For instance, we have a collection with three elements, the valid indexes are 0,1 and 2. This means three boxes, one label with 0, another one with 1, and the last box has the label 2. So if you try to access box number 3, you can’t, because it doesn’t exist. That’s when you get the java.lang.ArrayIndexOutOfBoundsException error.

The Simplest Case

Let’s see the simplest code snippet which will through this error:

public class IndexError {

    public static void main(String[] args){
        String[] fruits = {"Orange", "Pear", "Watermelon"};
        System.out.println(fruits[4]);
    }
}

Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 3

Although the error refer to arrays, you could also encounter the error when working with a List, which is also an indexed collection, meaning a collection where item can be accessed by their index.

import java.util.Arrays;
import java.util.List;
public class IndexError {

    public static void main(String[] args){
        List<String> fruits = Arrays.asList("Orange", "Pear", "Watermelon");
        System.out.println(fruits.get(4));
    }
}

Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 3

Example #1: Using invalid indexes in a loop

An instance where you might encounter the ArrayIndexOutOfBoundsException exception is when working with loops. You should make sure the index limits of your loop are valid in all the iterations. The loop shouldn’t try to access an item that doesn’t exist in the collection. Let’s see an example.

import java.util.Arrays;
import java.util.List;

public class IndexError {

    public static void main(String[] args){
        List<String> fruits = Arrays.asList("Orange", "Pear", "Watermelon");
        for(int index=0;index<=fruits.size();index++){
            System.out.println(fruits.get(index));
        }
    }
}

Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
Orange
Pear
Watermelon
	at java.base/java.util.Arrays$ArrayList.get(Arrays.java:4351)
	at com.hellocodeclub.IndexError.main(IndexError.java:11)

The code above will loop through every item in the list and print its value, however there is an exception at the end. The problem in this case is the stopping condition in the loop: index<=fruits.size(). This means that it will while index is less or equal to 3, therefore the index will start in 0, then 1, then 2 and finally 3, but unfortunately 3 is invalid index.

How to fix it – Approach #1

You can fix this error by changing the stopping condition. Instead of looping while the index is less or equal than 3, you can replace by “while index is less than 3”. Doing so the index will go through 0, 1, and 2, which are all valid indexes. Therefore the for loop should look as below:

for(int index=0;index<fruits.size();index++){

That’s all, really straightforward change once you understand the root cause of the problem. Here is how the code looks after the fix:

import java.util.Arrays;
import java.util.List;

public class IndexError {
    public static void main(String[] args){
        List<String> fruits = Arrays.asList("Orange", "Pear", "Watermelon");
        for(int index=0;index<fruits.size();index++){
            System.out.println(fruits.get(index));
        }
    }
}

Output:

Orange
Pear
Watermelon

How to fix it – Approach #2

Another way to avoid this issue is using the for each syntax. Using this approach, you don’t have to manage the index, since Java will do it for you. Here is how the code will look:

import java.util.Arrays;
import java.util.List;

public class IndexError {

    public static void main(String[] args){
        List<String> fruits = Arrays.asList("Orange", "Pear", "Watermelon");
        for(String fruit: fruits){
            System.out.println(fruit);
        }
    }
}

Example #2: Loop through a string

Another example. Imagine that you want to count the appearances of character ‘a’ in a given sentence. You will write a piece of code similar to the one below:

public class CountingA {

    public static void main(String[] args){
        String sentence = "Live as if you were to die tomorrow. Learn as if you were to live forever";
        char [] characters = sentence.toCharArray();
        int countA = 0;
        for(int index=0;index<=characters.length;index++){
            if(characters[index]=='a'){
                countA++;
            }
        }
        System.out.println(countA);
    }
}

Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 73 out of bounds for length 73
	at com.hellocodeclub.dev.CountingA.main(CountingA.java:8)

The issue in this case is similar to the one from the previous example. The stopping condition is the loop is right. You should make sure the index is within the boundaries.

How to fix it

As in the previous example, you can fix it by removing the equal from the stopping condition, or by using a foreach and therefore avoid managing the index. See below both fixes:

public class CountingA {
    public static void main(String[] args){
        String sentence = "Live as if you were to die tomorrow. Learn as if you were to live forever";
        int countA = 0;
        for(Character charater: sentence.toCharArray()){ // FOR EACH
            if(charater=='a'){
                countA++;
            }
        }
        System.out.println(countA);
    }
}

Output:

3

Conclusion

In summary, we have seen what the “java.lang.ArrayIndexOutOfBoundsException” error means . Additionally we covered how you can fix this error by making sure the index is within the collection boundaries, or using foreach syntax so you don’t need to manage the index.

I hope you enjoy this article, and understand this issue better to avoid it when you are programming.

Thank you so much for reading and supporting this blog!

Happy Coding!

Project-Based Programming Introduction

Steady pace book with lots of worked examples. Starting with the basics, and moving to projects, data visualisation, and web applications

100% Recommended book for Java Beginners

Unique lay-out and teaching programming style helping new concepts stick in your memory

90 Specific Ways to Write Better Python

Great guide for those who want to improve their skills when writing python code. Easy to understand. Many practical examples

Grow Your Java skills as a developer

Perfect Boook for anyone who has an alright knowledge of Java and wants to take it to the next level.

Write Code as a Professional Developer

Excellent read for anyone who already know how to program and want to learn Best Practices

Every Developer should read this

Perfect book for anyone transitioning into the mid/mid-senior developer level

Great preparation for interviews

Great book and probably the best way to practice for interview. Some really good information on how to perform an interview. Code Example in Java