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
4
votes
1 answer

ArrayIndexOutofBoundException when printing unicode words in jtext area. (Malayalam Words)

I am trying to print malayalam words fetched from rssfeeds provided by various medias like "Matrubhumi" "Indiavision" to a jtext area. What I am doing is saving all the topics from rssfeed to a text file and then reading them line by line to print…
4
votes
4 answers

Android List View Array Index Out Of Bounds Exception - No clues?

I have an app which loads a listview when opened, however I am getting an Array Index Out Of Bounds Exception, with no clues as to where the problem lies. It is trying to access index=-1 somewhere, but I have no idea where. The app loads Homework…
TomRichardson
  • 5,933
  • 5
  • 27
  • 30
4
votes
1 answer

ArrayList While Loop Gives IndexOutOfBoundsException

I am trying to write a method that determines the maximum value of an array list using tournament style comparisons. However, I guess I don't understand something about while loops because I cannot get the desired output and instead get an…
3
votes
5 answers

How to throw ArrayIndexOutOfBoundsException?

I have a method that checks spots in a 2D array, and it also checks if they are null. I want to throw the ArrayIndexOutOfBoundsException because I already check for null. I tried adding throws ArrayIndexOutOfBoundsException after declaring the…
jocopa3
  • 796
  • 1
  • 10
  • 29
3
votes
5 answers

Datagridview error System.IndexOutOfRangeException: Index 0 does not have a value

I am getting one error when I am trying to populate binding source. The exception is as follows; System.IndexOutOfRangeException: Index 0 does not have a value. at System.Windows.Forms.CurrencyManager.get_Item(Int32 index) at…
VJOY
  • 3,752
  • 12
  • 57
  • 90
3
votes
2 answers

java data types to byte array

I have a Java class public class MsgLayout{ int field1; String field2; long field3; } I have to write this object as a byte array in a Socket output stream. The three fields (instance variables) have a layout. i.e. field1 must occupy 1 byte, field2…
hoshang.varshney
  • 1,110
  • 3
  • 15
  • 26
3
votes
1 answer

Array index loop to begin instead of mem access error

I'm currently developping a vision system which is controlled/moonitored via a computer application that I'm writting in C/C++. If you are wondering why I,m writting in C/C++ its basically that my vision sensor (LMI Gocator 2490) has functions…
3
votes
0 answers

Update to androidx.appcompat:appcompat:1.3.0 causing 'indexOutOfBounds' crash

I recently updated my dependencies, including updating androidx.appCompat from 1.2.0 to 1.3.0. It took some digging to figure out that this is what was causing my crash. The crash doesn't occur until the user clicks on a MaterialCardView to…
3
votes
1 answer

"Condition is always 'true'" and "Array index is out of bounds" warnings

I'm trying to develop my first android app using android studio, and am getting a couple of warnings I can't seem to get rid of in an inner class constructor: In the for loop it warns that the termination condition is always true. However this…
3
votes
1 answer

Slice can access another slice out of range but indexing out of range causes panic

My code: package main import ( "fmt" ) func main() { a := [10]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} b := a[1:4] fmt.Println("a:", a) fmt.Println("b:", b) // Works fine even though c is indexing past the end of b. c :=…
Lone Learner
  • 18,088
  • 20
  • 102
  • 200
3
votes
0 answers

RecyclerView Inconsistency detected. Invalid view holder adapter positionb - crash on some devices

I'm not able to recreate this crash with my Pixel4XL, but it's occuring a lot in the past days. I cannot find out something that the devices on which it is crashing have in common. I'm glad that I implemented Crashlytics before. Thanks to the custom…
3
votes
1 answer

I keep getting a "java.lang.StringIndexOutOfBoundsException" even though my for loop counter adjusts for length by subtracting 1

So my main goal is to create a program that can decrypt a caesar cipher. I have everything set up so that I have the regular alphabet set up in one array and then a decoder array where I have shifted the alphabet based on a shift/key the user…
3
votes
1 answer

How can I populate a vector in reverse?

I've got a vector: let v = Vec::with_capacity(10); I want to populate it with data, in reverse order: let i = 10; while i > 0 { i -= 1; v[i] = non_pure_function(i); } Unfortunately, this panics; when allocating with Vec::with_capacity,…
wizzwizz4
  • 6,140
  • 2
  • 26
  • 62
3
votes
1 answer

Out of bounds exception despite loops being in range of array length

So the program is supposed to make an odd sized array between the sizes of 3 and 11 from user input and then fill that board with a character at certain places to get patterns. Everything was going fine until I tried returning the array which gave…
3
votes
1 answer

Exception when removing elements from ArrayList?

I am filling an ArrayList al with random integers. Then when I try to remove them i'm getting these errors: Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 5000 out-of-bounds for length 5000 at …
user8606118