Array index is out of bounds java как исправить

What causes ArrayIndexOutOfBoundsException?

If you think of a variable as a “box” where you can place a value, then an array is a series of boxes placed next to each other, where the number of boxes is a finite and explicit integer.

Creating an array like this:

final int[] myArray = new int[5]

creates a row of 5 boxes, each holding an int. Each of the boxes has an index, a position in the series of boxes. This index starts at 0 and ends at N-1, where N is the size of the array (the number of boxes).

To retrieve one of the values from this series of boxes, you can refer to it through its index, like this:

myArray[3]

Which will give you the value of the 4th box in the series (since the first box has an index of 0).

An ArrayIndexOutOfBoundsException is caused by trying to retrieve a “box” that does not exist, by passing an index that is higher than the index of the last “box”, or negative.

With my running example, these code snippets would produce such an exception:

myArray[5] //tries to retrieve the 6th "box" when there is only 5
myArray[-1] //just makes no sense
myArray[1337] //way to high

How to avoid ArrayIndexOutOfBoundsException

In order to prevent ArrayIndexOutOfBoundsException, there are some key points to consider:

Looping

When looping through an array, always make sure that the index you are retrieving is strictly smaller than the length of the array (the number of boxes). For instance:

for (int i = 0; i < myArray.length; i++) {

Notice the <, never mix a = in there..

You might want to be tempted to do something like this:

for (int i = 1; i <= myArray.length; i++) {
    final int someint = myArray[i - 1]

Just don’t. Stick to the one above (if you need to use the index) and it will save you a lot of pain.

Where possible, use foreach:

for (int value : myArray) {

This way you won’t have to think about indexes at all.

When looping, whatever you do, NEVER change the value of the loop iterator (here: i). The only place this should change value is to keep the loop going. Changing it otherwise is just risking an exception, and is in most cases not necessary.

Retrieval/update

When retrieving an arbitrary element of the array, always check that it is a valid index against the length of the array:

public Integer getArrayElement(final int index) {
    if (index < 0 || index >= myArray.length) {
        return null; //although I would much prefer an actual exception being thrown when this happens.
    }
    return myArray[index];
}

The ArrayIndexOutOfBoundsException is a runtime exception in Java that occurs when an array is accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.

Since the ArrayIndexOutOfBoundsException is an unchecked exception, it does not need to be declared in the throws clause of a method or constructor.

What Causes ArrayIndexOutOfBoundsException

The ArrayIndexOutOfBoundsException is one of the most common errors in Java. It occurs when a program attempts to access an invalid index in an array i.e. an index that is less than 0, or equal to or greater than the length of the array.

Since a Java array has a range of [0, array length – 1], when an attempt is made to access an index outside this range, an ArrayIndexOutOfBoundsException is thrown.

ArrayIndexOutOfBoundsException Example

Here is an example of a ArrayIndexOutOfBoundsException thrown when an attempt is made to retrieve an element at an index that falls outside the range of the array:

public class ArrayIndexOutOfBoundsExceptionExample {
    public static void main(String[] args) {
        String[] arr = new String[10]; 
        System.out.println(arr[10]);
    }
}

In this example, a String array of length 10 is created. An attempt is then made to access an element at index 10, which falls outside the range of the array, throwing an ArrayIndexOutOfBoundsException:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 10
    at ArrayIndexOutOfBoundsExceptionExample.main(ArrayIndexOutOfBoundsExceptionExample.java:4)

How to Fix ArrayIndexOutOfBoundsException

To avoid the ArrayIndexOutOfBoundsException, the following should be kept in mind:

  • The bounds of an array should be checked before accessing its elements.
  • An array in Java starts at index 0 and ends at index length - 1, so accessing elements that fall outside this range will throw an ArrayIndexOutOfBoundsException.
  • An empty array has no elements, so attempting to access an element will throw the exception.
  • When using loops to iterate over the elements of an array, attention should be paid to the start and end conditions of the loop to make sure they fall within the bounds of an array. An enhanced for loop can also be used to ensure this.

Track, Analyze and Manage Errors With Rollbar

Rollbar in action

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever. Sign Up Today!


Posted by Marta on March 28, 2023

Viewed 8656 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:

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:

What next?

In case you would like to continue learning, and get a good understanding of the language concepts, I will recommend you check out the following course on Udemy:

Java for absolute Beginners

This course covers all the fundamentals and practice exercises to strengthen your coding knowledge. Or you can also follow one of the tutorials below, however those videos will require you to understand the fundamental, such as classes and objects.

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!

rock paper scissors java
java coding interview question
tic tac toe java

Java supports the creation and manipulation of arrays as a data structure. The index of an array is an integer value that has value in the interval [0, n-1], where n is the size of the array. If a request for a negative or an index greater than or equal to the size of the array is made, then the JAVA throws an ArrayIndexOutOfBounds Exception. This is unlike C/C++, where no index of the bound check is done.

The ArrayIndexOutOfBoundsException is a Runtime Exception thrown only at runtime. The Java Compiler does not check for this error during the compilation of a program.

Java

public class NewClass2 {

    public static void main(String[] args)

    {

        int ar[] = { 1, 2, 3, 4, 5 };

        for (int i = 0; i <= ar.length; i++)

            System.out.println(ar[i]);

    }

}

Expected Output: 

1
2
3
4
5

Original Output:

Runtime error throws an Exception: 

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
    at NewClass2.main(NewClass2.java:5)

Here if you carefully see, the array is of size 5. Therefore while accessing its element using for loop, the maximum index value can be 4, but in our program, it is going till 5 and thus the exception.

Let’s see another example using ArrayList:

Java

import java.util.ArrayList;

public class NewClass2

{

    public static void main(String[] args)

    {

        ArrayList<String> lis = new ArrayList<>();

        lis.add("My");

        lis.add("Name");

        System.out.println(lis.get(2));

    }

}

Runtime error here is a bit more informative than the previous time- 

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
    at java.util.ArrayList.rangeCheck(ArrayList.java:653)
    at java.util.ArrayList.get(ArrayList.java:429)
    at NewClass2.main(NewClass2.java:7)

Let us understand it in a bit of detail:

  • Index here defines the index we are trying to access.
  • The size gives us information on the size of the list.
  • Since the size is 2, the last index we can access is (2-1)=1, and thus the exception.

The correct way to access the array is : 
 

for (int i=0; i<ar.length; i++){

}

Correct Code – 

Java

public class NewClass2 {

    public static void main(String[] args)

    {

        int ar[] = { 1, 2, 3, 4, 5 };

        for (int i = 0; i < ar.length; i++)

            System.out.println(ar[i]);

    }

}

Handling the Exception:

1. Using for-each loop: 

This automatically handles indices while accessing the elements of an array.

Syntax: 

for(int m : ar){
}

Example:

Java

import java.io.*;

class GFG {

    public static void main (String[] args) {

          int arr[] = {1,2,3,4,5};

          for(int num : arr){

             System.out.println(num);    

        }

    }

}

2. Using Try-Catch: 

Consider enclosing your code inside a try-catch statement and manipulate the exception accordingly. As mentioned, Java won’t let you access an invalid index and will definitely throw an ArrayIndexOutOfBoundsException. However, we should be careful inside the block of the catch statement because if we don’t handle the exception appropriately, we may conceal it and thus, create a bug in your application.

Java

public class NewClass2 {

    public static void main(String[] args)

    {

        int ar[] = { 1, 2, 3, 4, 5 };

        try {

            for (int i = 0; i <= ar.length; i++)

                System.out.print(ar[i]+" ");

        }

        catch (Exception e) {

            System.out.println("nException caught");

        }

    }

}

Output

1 2 3 4 5 
Exception caught

Here in the above example, you can see that till index 4 (value 5), the loop printed all the values, but as soon as we tried to access the arr[5], the program threw an exception which is caught by the catch block, and it printed the “Exception caught” statement.

Explore the Quiz Question.
This article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect or you want to share more information about the topic discussed above.

Last Updated :
08 Feb, 2023

Like Article

Save Article

How to fix an Array Index Out Of Bounds Exception in Java

In this article, we will look at An Array Index Out Of Bounds Exception in Java, which is the common exception you might come across in a stack trace. An array Index Out Of Bounds Exception is thrown when a program attempts to access an element at an index that is outside the bounds of the array. This typically occurs when a program tries to access an element at an index that is less than 0 or greater than or equal to the length of the array.

What causes an ArrayIndexOutOfBoundsException

This can happen if the index is negative or greater than or equal to the size of the array. It indicates that the program is trying to access an element at an index that does not exist. This can be caused by a bug in the code, such as a off-by-one error, or by user input that is not properly validated.

Here is an example in Java

int[] numbers = {1, 2, 3, 4, 5};

try {
    int x = numbers[5]; // this will throw an ArrayIndexOutOfBoundsException
    System.out.println(x);
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Error: Index is out of bounds.");
}

In this example, the array numbers has a length of 5, but the program is trying to access the element at index 5, which does not exist. The try block contains the code that may throw the exception and the catch block contains the code that will handle the exception if it is thrown. In this case, it will print the message “Error: Index is out of bounds.”

Another example:

int[] numbers = {1, 2, 3, 4, 5};
int index = -1;
try {
    int x = numbers[index]; // this will throw an ArrayIndexOutOfBoundsException
    System.out.println(x);
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Error: Index is out of bounds.");
}

In this example, the variable index is assigned -1 and when we use it to access the element of the array, it will throw an exception because the index is negative and not valid.

It’s important to note that, this kind of exception can also be thrown when working with other Java collection classes like ArrayList, Vector, etc.

How to fix an ArrayIndexOutOfBoundsException

There are several ways to fix an ArrayIndexOutOfBoundsException:

  1. Validate user input: If the exception is caused by user input, make sure to validate the input to ensure that it is within the valid range of indices for the array. For example, in the second example I provided above, you can check if the index is greater than or equal to 0 and less than the size of the array before trying to access the element.
  2. Use a for loop with the size of the array: Instead of using a traditional for loop with a fixed number of iterations, you can use a for loop that iterates over the array based on its size. This way, the loop will not try to access an element that does not exist.

    for (int i = 0; i < numbers.length; i++) {
        int x = numbers[i];
        System.out.println(x);
    }
    
  3.  Use a try-catch block: If you are unable to validate the input or change the loop, you can use a try-catch block to catch the exception and handle it in your code. For example, you can display an error message, or set a default value for the variable.
    try {
        int x = numbers[index];
        System.out.println(x);
    } catch (ArrayIndexOutOfBoundsException e) {
        System.out.println("Error: Index is out of bounds.");
    }
    

    It’s also important to note that you should always check if the array is null before trying to access its elements.  If you reference an array element that is out of bounds, it can cause a NullPointerException.  Additionally, it’s good practice to always validate the user input and the index of the array before trying to access the elements to avoid this kind of exception.

I am text block. Click edit button to change this text. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.

How to find the ArrayIndexOutOfBoundsException in a Java application

To find the Array Index Out Of Bounds Exception in a Java application, you can use a combination of the following methods:

  • Add try-catch blocks around the code that is causing the exception. The catch block can contain a print statement or a logging statement to print the exception message and the stack trace.
  • Use a debugger to step through the code and check the values of variables at each step. This can help you identify the specific line of code causing the exception and the values of the variables involved.
  • Enable logging for your application and check the log files for any error messages or stack traces related to the Array Index Out Of Bounds Exception.
  • Use an Application Performance Management (APM) tool like FusionReactor to monitor your application for errors and exceptions. This can provide detailed information about the exception, such as the line number and method name.

It’s important to remember that the ArrayIndexOutOfBoundsException is thrown when an illegal index is used to access an array. This can happen because of a bug in your code using an index that is out of bounds or because of a problem with the input data. Therefore, check the input data causing the exception and validate it.

Watch this video and see how FusionReactor Event Snapshot takes you straight to the root cause of an ArrayIndexOutOfBoundsException in a single click

Conclusion – How to fix an ArrayIndexOutOfBoundsException in Java

Following these steps, you can fix an ArrayIndexOutOfBoundsException in your Java program. Remember, the key is to always check the bounds of the array before attempting to access any elements. For more information on common Java errors, see our posts about ClassNotFoundExcetion, What causes a NoSuchMethodError in Java and how to avoid it, and java.lang.OutofMemoryException. Want to learn more about stack traces? See our post “What is a Java Stack Trace? How to Interpret and Understand it to Debug Problems in your applications”.

Recent Posts

Recent Posts

Добавить комментарий