Questions tagged [indexoutofboundsexception]

An exception that occurs when you attempt to access an object that is outside the boundaries of the container. Common containers are arrays or array-based objects. This is a language-independent tag.

An IndexOutOfBoundsException is an exception that occurs when you attempt to access an object that is outside the boundaries of the container. Common containers are arrays or array-based objects.

IndexOutOfBoundsExceptions are generally caused by one of 2 things...

  1. Passing a negative pointer index
  2. Passing a pointer that is equal-to, or greater than the length of the container.

If we use the example of an array which is defined as being able to hold 4 objects...

Object[] myArray = new Object[4];

Arrays, and array-based containers, in most languages have zero-based references (See Wikipedia for a list of exceptions). This means that the first item in the array is myArray[0], not myArray[1]. For new programmers, this is often not obvious, and can result in them trying to reference objects from 1-4 rather than 0-3. This causes the programmer to receive an IndexOutOfBoundsException when trying to reference myArray[4].

A common way to make this mistake is to use a for loop as follows:

for (int i=0; i<=myArray.Length; i++)
    // do something with myArray[i];

This will fail with an IndexOutOfBoundsException because only elements [0] through [3] exist. myArray[myArray.Length] is myArray[4], which does not exist.

Similarly, trying to reference a negative index, such as myArray[-1] will fail, as it exists outside the bounds of the array. This would commonly occur when trying to obtain an index reference from another method, where the method is using a negative number to indicate a failure.

For example, assume the following code...

String myName = "Fred";
Object myObject = myArray[myName.getIndexOf("B")];

In this example, the getIndexOf("B") method will find the position of the letter B in the given String. However, when trying to use this method in the code above, the letter B is not found in the word Fred, therefore it returns -1 to indicate it was not found. If we then attempt to use that value as a reference to an item of an array, it will fail.

To help avoid these exceptions, it is usually good practice to perform a check before attempting to reference an item of a collection. For example...

int indexPointer = 2;
if (indexPointer >= 0 && indexPointer < myArray.length){
    // the index is within the bounds of the array
    Object myObject = myArray[indexPointer];
}

Canonical Question/Answers:

2854 questions
6
votes
5 answers

Error inflating xml layout ArrayIndexOutOfBoundsException on TextView

I ran into a weird crash problem. I can't quite seem to figure out the problem. Here is the crash report. java.lang.RuntimeException: Unable to start activity…
6
votes
1 answer

ArrayIndexOutOfBoundsException without any reason

hey in my map activity when user clicks on marker application crashes and I'm getting this in logcat which is not caused by a class from my application and I can't find out why I'm getting that E/AndroidRuntime: FATAL EXCEPTION: main Process:…
Amir_P
  • 8,322
  • 5
  • 43
  • 92
6
votes
4 answers

How to fix java.lang.ArrayIndexOutOfBoundsException: length=1; index=1

I am creating an android application that consists of a serial communication.I am getting an error called java.lang.ArrayIndexOutOfBoundsException: length=1; index=1 please tell me how to fix it This is my usb driver: public class UsbDriver { …
RD Division Medequip
  • 1,605
  • 4
  • 18
  • 32
6
votes
1 answer

Why does CppCheck give an array access out of bounds error for this static const array?

CppCheck 1.67 has identified and array accessed out of bounds error on one of my projects. I didn't think the code was wrong, so I have stripped down the code to the bare minimum example that still raises the same error. Why does CppCheck give the…
6
votes
1 answer

SQL query on H2 database table throws ArrayIndexOutOfBoundsException

I have a H2 database on which some queries work, while others are throwing an ArrayIndexOutOfBoundsException. For example: SELECT COLUMN_1 FROM MY_TABLE; // works fine SELECT COUNT(COLUMN_1) FROM MY_TABLE; // gives following error message: [Error…
Kaadzia
  • 1,393
  • 1
  • 14
  • 34
6
votes
1 answer

Creating a tree data structure in java?

I am trying to create a tree data structure in java where each parent node can have only three child nodes but I'm stuck on adding a node to the tree in the case where a node has at least one child but less than 3 child nodes. I'm unsure if I should…
6
votes
1 answer

Is it OK to use exceptions to check for array boundaries?

I want to check whether the given coordinates are withing an array or not. public boolean checkBounds(int x, int y) { try { Object val = array[x][y]; return true; } catch (ArrayIndexOutOfBoundsException e) { return…
Dariusz
  • 21,561
  • 9
  • 74
  • 114
6
votes
10 answers

ArrayIndexOutOfBoundsException not being caught and ignored

I want to catch and ignore and ArrayIndexOutOfBoundsException error (basically it's not something I have control over, so I need my program to keep chugging along). However my try/catch pair doesn't seem to catch the exception and ignore it.…
Ankur
  • 50,282
  • 110
  • 242
  • 312
6
votes
2 answers

When using ".Get(0)" on an empty list, I get an out of bounds exception and not null?

So in my homework assignment, for my error checking testing stuff I do a get on a List and I get an IndexOutOfBoundsException. I solve it by using a check on .isEmpty but what I would like to know why doesn't: boolean b = myList.Get(0)…
RaenirSalazar
  • 556
  • 1
  • 7
  • 20
6
votes
1 answer

Another java.lang.IndexOutOfBoundsException, but index < size

I've just ported all my arrays to ArrayList (due to my great lack of knowledge in Java I didn't know basic Array type does not have any ".add" option) in my little program and everything seems fine... except that from time to time an exception is…
LosTChG
  • 77
  • 2
  • 7
5
votes
1 answer

Compose BottomSheetScaffold IndexOutOfBoundsException application crash

I searched for a solution related to this issue but found nothing. I solved the problem so I'm posting the problem and the solution here with goal of helping someone. Problem description After updating Jetpack Compose from version 1.2.0-beta02 to…
5
votes
5 answers

RecyclerView: Inconsistency detected. Invalid item position - why is that?

Our QA has detected a bug: the following RecyclerView-related crash happened: ` java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid item position 2(offset:2).state:3 A brutal workaround could be perhaps to catch the…
5
votes
3 answers

Loading all values of 2d array in java

I'm attempting to create a 2d puzzle slider game. I created my own object called gamestate to store the parent gamestate and the new gamestate, as I plan on solving it using BFS. A sample array will look like int[][] tArr =…
Matthrew
  • 71
  • 3
5
votes
1 answer

Spark distinct followed by join giving IndexOutOfBoundsException

Trying to join two dataframes A & B. B has a distinct operation right before the join. Also one of the columns in B is joined on two columns in A. This specific situation is giving an IndexOutOfBoundsException. Anyone run into this situation…
r4j1v
  • 135
  • 1
  • 1
  • 5
5
votes
4 answers

Finding the index of the smallest element in an array (Java)

I am trying to write up a block of code that takes an array of integers as an argument and returns the index of the smallest element in the array. Also, the function should return -1 if the list is an empty list. So far I have got, public static…
user430574
  • 305
  • 1
  • 2
  • 10