Error java lang arrayindexoutofboundsexception java

What does ArrayIndexOutOfBoundsException mean and how do I get rid of it? Here is a code sample that triggers the exception: String[] names = { "tom", "bob", "harry" }; for (int i = 0; i <= n...

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

1. Overview

In this tutorial, we’ll discuss ArrayIndexOutOfBoundsException in Java. We’ll understand why it occurs and how to avoid it.

2. When Does ArrayIndexOutOfBoundsException Occur?

As we know, in Java, an array is a static data structure, and we define its size at the time of creation.

We access the elements of an array using indices. Indexing in an array starts from zero and must never be greater than or equal to the size of the array.

In short, the rule of thumb is 0 <= index < (size of array).

ArrayIndexOutOfBoundsException occurs when we access an array, or a Collection, that is backed by an array with an invalid index. This means that the index is either less than zero or greater than or equal to the size of the array.

Additionally, bound checking happens at runtime. So, ArrayIndexOutOfBoundsException is a runtime exception. Therefore, we need to be extra careful when accessing the boundary elements of an array.

Let’s understand some of the common operations that lead to ArrayIndexOutOfBoundsException.

2.1. Accessing an Array

The most common mistake that may happen while accessing an array is forgetting about the upper and lower bounds.

The lower bound of an array is always 0, while the upper bound is one less than its length.

Accessing the array elements out of these bounds would throw an ArrayIndexOutOfBoundsException:

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

Here, the size of the array is 5, which means the index will range from 0 to 4.

In this case, accessing the 5th index results in an ArrayIndexOutOfBoundsException:

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

Similarly, we get ArrayIndexOutOfBoundsException if we pass a value less than zero as an index to numbers.

2.2. Accessing a List Returned by Arrays.asList()

The static method Arrays.asList() returns a fixed-sized list that is backed by the specified array. Moreover, it acts as a bridge between array-based and collection-based APIs.

This returned List has methods to access its elements based on indices. Also, similar to an array, the indexing starts from zero and ranges to one less than its size.

If we try to access the elements of the List returned by Arrays.asList() beyond this range, we would get an ArrayIndexOutOfBoundsException:

List<Integer> numbersList = Arrays.asList(1, 2, 3, 4, 5);
int lastNumber = numbersList.get(5);

Here again, we are trying to get the last element of the List. The position of the last element is 5, but its index is 4 (size – 1). Hence, we get ArrayIndexOutOfBoundsException as below:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
    at java.base/java.util.Arrays$ArrayList.get(Arrays.java:4351)
    at  ...

Similarly, if we pass a negative index, say -1, we will get a similar result.

2.3. Iterating in Loops

Sometimes, while iterating over an array in a for loop, we might put a wrong termination expression.

Instead of terminating the index at one less than the length of the array, we might end up iterating until its length:

int sum = 0;
for (int i = 0; i <= numbers.length; i++) {
    sum += numbers[i];
}

In the above termination expression, the loop variable is being compared as less than or equal to the length of our existing array numbers. So, in the last iteration, the value of will become 5.

Since index 5 is beyond the range of numbers, it will again lead to ArrayIndexOutOfBoundsException:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
    at com.baeldung.concatenate.IndexOutOfBoundExceptionExamples.main(IndexOutOfBoundExceptionExamples.java:22)

3. How to Avoid ArrayIndexOutOfBoundsException?

Let’s now understand some ways to avoid ArrayIndexOutOfBoundsException.

3.1. Remembering the Start Index

We must always remember that the array index starts at 0 in Java. So, the first element is always at index 0, while the last element is at index one less than the length of the array.

Remembering this rule will help us avoid ArrayIndexOutOfBoundsException most of the time.

3.2. Correctly Using the Operators in Loops

Incorrectly initializing the loop variable to index 1 may result in ArrayIndexOutOfBoundsException.

Similarly, the incorrect use of operators <, <=, > or >= in termination expressions of loops is a common reason for the occurrence of this exception.

We should correctly determine the use of these operators in loops.

3.3. Using Enhanced for Loop

If our application is running on Java 1.5 or a higher version, we should use an enhanced for loop statement that has been specifically developed to iterate over collections and arrays. Also, it makes our loops more succinct and easy to read.

Additionally, using the enhanced for loop helps us completely avoid the ArrayIndexOutOfBoundsException as it does not involve an index variable:

for (int number : numbers) {
    sum += number;
}

Here, we do not have to worry about indexing. The enhanced for loop picks up an element and assigns it to a loop variable, number, with each iteration. Thus, it completely avoids ArrayIndexOutOfBoundsException.

4. IndexOutOfBoundsException vs. ArrayIndexOutOfBoundsException

IndexOutOfBoundsException occurs when we try to access an index of some type (String, array, List, etc.) beyond its range. It’s a superclass of ArrayIndexOutOfBoundsException and StringIndexOutOfBoundsException.

Similar to ArrayIndexOutOfBoundsException, StringIndexOutOfBoundsException is thrown when we try to access a character of a String with an index beyond its length.

5. Conclusion

In this article, we explored ArrayIndexOutOfBoundsException, some examples for how it occurs, and some common techniques to avoid it.

As always, the source code for all of these examples is available over on GitHub.

Posted by Marta on March 4, 2022 Viewed 6033 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:

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.

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.lang.ArrayindexOutOfboundsException is Runtime and Unchecked Exception. It’s subclass of java.lang IndexOutOfBoundsException.

ArrayIndexOutOfBoundsException is most common error in Java Program. It throws when an array has been accessed with an illegal index either negative or greater than or equal to the size of the array.

Points To Remember:

  •  Array index starts at zero and goes to length – 1, for example in an integer array int[] counts= new int[20], the first index would be zero and last index out be 19 (20 -1)
  • Array index cannot be negative, hence counts[-1] will throw java.lang.ArrayIndexOutOfBoundsException.
  • The maximum array index can be Integer.MAX_VALUE -1 because array accept data type of index is int and max allowed value for int is Integer.MAX_VALUE.

Constructors:

  • ArrayIndexOutOfBoundsException() : Constructs an  ArrayIndexOutOfBoundsException with no detail message.
  • ArrayIndexOutOfBoundsException(int index) : Constructs a new ArrayIndexOutOfBoundsException class with an argument indicating the illegal index.
  • ArrayIndexOutOfBoundsException(String s) : Constructs an ArrayIndexOutOfBoundsException class with the specified detail message.

Example :

public class ArrayOutOfBoundException {

	public static void main(String[] args) {
		String [] empArr={"Saurabh","Gaurav","Shailesh","Ankur","Ranjith","Ramesh"};
		//No of employee in array
		//Will through IndexOuhtOfBoundException because array having only six element of index 0 to 5
		try
		{
		String name=empArr[8];
		System.out.println("Employee :"+empArr[8]);
		}
		catch(ArrayIndexOutOfBoundsException ex)
		{
			ex.printStackTrace();
		}
	}
}

Output:

java.lang.ArrayIndexOutOfBoundsException: 8
	at example.ArrayIndexOutOfBoundsException.main(ArrayIndexOutOfBoundsException.java:11)<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>

“Learn From Others Experience»

Понравилась статья? Поделить с друзьями:
  • Error java invalid source release 13 intellij idea
  • Error java installer что делать
  • Error job failed exit code 125
  • Error job failed exit code 1 gitlab
  • Error job failed custom executor is missing runexec