Index 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];
}

ArrayIndexOutOfBoundsException – это исключение, появляющееся во время выполнения. Оно возникает тогда, когда мы пытаемся обратиться к элементу массива по отрицательному или превышающему размер массива индексу. Давайте посмотрим на примеры, когда получается ArrayIndexOutOfBoundsException в программе на Java.

Попробуйте выполнить такой код:

    static int number=11;
    public static String[][] transactions=new String[8][number];
    public static void deposit(double amount){
        transactions[4][number]="deposit";
        number++;
    }

    public static void main(String[] args) {
        deposit(11);
    }
}

Вы увидите ошибку:

Caused by: java.lang.ArrayIndexOutOfBoundsException: 0
	at sample.Main.deposit(Main.java:22)
	at sample.Main.main(Main.java:27)
Exception running application sample.Main

Process finished with exit code 1

Что здесь произошло? Ошибка в строке 27 – мы вызвали метод deposit(), а в нем уже, в строке 22 – попытались внести в поле массива значение «deposit». Почему выкинуло исключение? Дело в том, что мы инициализировали массив размера 11 (number = 11), н опопытались обратиться к 12-му элементу. Нумерация элементов массива начинается с нуля. Так что здесь надо сделать, например, так

public static String[][] transactions=new String[8][100];

Но вообще, это плохой код, так писать не надо. Давайте рассмотрим еще один пример возникновения ошибки ArrayIndexOutOfBoundsException:

public static void main(String[] args) {
    Random random = new Random();
    int [] arr = new int[10];
    for (int i = 0; i <= arr.length; i++) {
       arr[i] =  random.nextInt(100);
       System.out.println(arr[i]);
    }
}

Здесь массив заполняется случайными значениями. При выполнении IntelliJ IDEA выдаст ошибку

Caused by: java.lang.ArrayIndexOutOfBoundsException: 10
	at sample.Main.main(Main.java:37)

В строке 37 мы заносим значение в массив. Ошибка возникла помтому, что индекса 10 нет в массиве arr, поэтому условие цикла i <= arr.length надо поменять на i < arr.length

Конструкция try для ArrayIndexOutOfBoundsException

ArrayIndexOutOfBoundsException можно обработать с помощью конструкции try-catch. Для этого оберните try то место, где происходит обращение к элементу массива по индексу, например, заносится значение. Как-то так:

try {
    array[index] = "что-то";
}
catch (ArrayIndexOutOfBoundsException ae){
    System.out.println(ae);
}

Но я бы рекомендовал вам все же не допускать данной ошибки, писать код таким образом, чтобы не пришлось ловить исключение ArrayIndexOutOfBoundsException.


Автор этого материала — я — Пахолков Юрий. Я оказываю услуги по написанию программ на языках Java, C++, C# (а также консультирую по ним) и созданию сайтов. Работаю с сайтами на CMS OpenCart, WordPress, ModX и самописными. Кроме этого, работаю напрямую с JavaScript, PHP, CSS, HTML — то есть могу доработать ваш сайт или помочь с веб-программированием. Пишите сюда.

тегизаметки, ArrayIndexOutOfBoundsException, 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

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!

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

Понравилась статья? Поделить с друзьями:
  • Index 25 size 5 minecraft ошибка
  • Index 0 size 0 ошибка zona
  • Indesit стиральная машина мигает ошибки
  • Indesit стиральная машина коды ошибок аркадия
  • Indesit ошибки f01 для стиральной машины