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
3
votes
0 answers

Android Databinding Error for Multiple Layout files

I am getting an error on using with android datat binding librery i have successfully compleated one layout it working. but i created new layout and add tag in new .xml and Build->clean project then getting an error * What went wrong: …
3
votes
1 answer

Unable to read all the data existing in excel sheet using Java/Selenium script

I'm facing an issue with reading the data from an excel file (which basically contains the login credentials in the form of test data) particularly when I am using TestNG. The same code works fine when I run it as a normal java program: Issue…
3
votes
4 answers

IndexOutOfBoundsException when running Dijkstra's algorithm implementation

Not particularly sure what's causing this IndexOutOfBoundsException to occur. The code works perfectly find if I hard code all of the addFlightPath() parameters, but as soon as I attempt to use a for loop to populate the flightPaths arrayList an…
user10127681
3
votes
1 answer

How can I access an array with an array of indexes in python?

I would like to access a multidimensional python array with an array of indexes, using the whole array to index the target element. Let me explain it better: A = np.arange(4).reshape(2,2) a = [1,1] >>> A[a[0],a[1]] 3 My intention is to pass the…
Marco
  • 33
  • 3
3
votes
1 answer

Is it possible to configure Python interpreter to provide more useful info on errors?

For example, can "IndexError: list index out of range" actually say what value in which variable caused the error and what the bound was? Eg. rather than bare a[i][j] += max(a[i][j-d], a[i-1][j]) IndexError: list index out of range Get…
3
votes
3 answers

IndexOutOfBoundsException for for-loop in Kotlin

I have two lists in Kotlin, of the same size, foodObjects: MutableList? and checked: MutableList?. I need to do a for loop and get the objectId from foodObjects every time that an element of checked is true. So it is this in…
ste9206
  • 1,822
  • 4
  • 31
  • 47
3
votes
3 answers

Recyclerview binds index out of list size after adding items

I have a RecyclerView with a LinearLinearManager. My method addItems() downloads data from the Internet and then adds 10 items one after the other like this: itemIds.add(id); listAdapter.notifyItemInserted(itemIds.size() - 1); I call this method…
3
votes
4 answers

How to substring a given string with specific rules in java

This is my code and it is showing error at while.Index out of bound exception is coming.The substrings should be such that Max 50 characters per string No number should be broken - for example " 4318, 4466, 486," is acceptable but " 4318, 4466,…
riya
  • 33
  • 6
3
votes
1 answer

"Index was outside the bounds of the array" when adding an item to a generic list

I just had a unique error where a live site was throwing "Index was outside the bounds of the array" on login. I tracked the error down to an old "timing" file inherited from an old project. Here's the full class public class TimingObject { …
roryok
  • 9,325
  • 17
  • 71
  • 138
3
votes
2 answers

c# Parallel For Loop index exceptions after removing the element

In my algorithm, what I am trying to do is following. while (R.Count > 0) { //R is also List() var N = new List(); var first = R[0]; N.Add(first); R.Remove(first); //below commented code runs just fine but…
3
votes
2 answers

Accessing negative index of vector via operator[] and .at()

vector input = {1, 2, 3, 4, 17, 117, 517, 997}; cout<< "input vector at index -1 is: " << input[-1] < input = {1, 2, 3, 4,…
Feng
  • 67
  • 1
  • 9
3
votes
3 answers

Java-Storing characters of a string in an array

for (int j = 0; j <= l - 1; j++) { char c1 = str.charAt(j); n[j] = c1; } //It is showing error-arrayIndexoutofbounds 'str' is an inputted string and 'l' is the length of the string str. I have to store all its character in an array…
Tanz
  • 41
  • 1
  • 1
  • 8
3
votes
4 answers

How to display a detailed error message using try{ }catch(){ } blocks

Suppose in your program you might get an IndexOutOfBoundsException. i am handling it in the following way: try{ //throws an IndexOutOfBoundsException during runtime }catch(IndexOutOfBoundsException ex){ System.err.println(ex); } This will only…
3
votes
2 answers

When I select radio button my app crashed

I have 3 Radio buttons each radio buttons to do some performs, Using this Radio Buttons I am filtering my Results E.g for RB1 for DATE-WISE RB2 for customernames and RB3 for Productname. Above two radio buttons working good(RB2 and RB3), but when I…
3
votes
1 answer

ArrayOutOfBoundsException while reading Image from Disk

At the moment I'm trying to print some pdfs in java. The API used is Apache PDF Box in Version 2.0. After converting the images I write them to disk to save memory. In the next step I read them again and write the title in the head of the image.…
finder2
  • 842
  • 1
  • 11
  • 30