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
20
votes
4 answers

NSArray out of bounds check

noobie question.. What is the best way to check if the index of an NSArray or NSMutableArray exists. I search everywhere to no avail!! This is what I have tried: if (sections = [arr objectAtIndex:4]) { /*.....*/ } or sections = [arr…
spacebiker
  • 3,777
  • 4
  • 30
  • 49
20
votes
3 answers

Checking out of bounds in Java

I'm trying to check if an array location is out of bounds, what's the simplest way? int[] arr; populate(arr); if(arr[-1] == null) //out of bounds! Would something like this work? I'm pretty sure this can be done with a trycatch or a scanner but for…
dukevin
  • 22,384
  • 36
  • 82
  • 111
18
votes
3 answers

Android app crash in play store prelaunch report but working in real device

Not able to track crash in the project, I got this error in play store pre-launch section, it showing on click of EditText, it got the error. but not getting any crash on a real device. Issue: java.lang.IndexOutOfBoundsException: setSpan (4 ... 4)…
18
votes
10 answers

IndexOutOfBoundsException when adding to ArrayList at index

I get exception Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0 for the below code. But couldn't understand why. public class App { public static void main(String[] args) { ArrayList s = new…
Bala
  • 11,068
  • 19
  • 67
  • 120
18
votes
4 answers

Strange ArrayIndexOutOfBoundsException for Java SimpleDateFormat

We run Java 1.4. We have this method: static SimpleDateFormat xmlFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); public static Date fromXml(String xmlDateTime) { ParsePosition pp = new ParsePosition(0); return…
lulu88
  • 1,694
  • 5
  • 27
  • 41
17
votes
0 answers

IndexOutOfBoundsException on Samsung devices

I'm getting an IndexOutOfBoundsException on Samsung Galaxy S5 and Note 3 and 4. It doesn't reference my code. Has anyone encountered this? I haven't been able to find anything on here. It appears to be occasionally happening when try to long-click…
ono
  • 2,984
  • 9
  • 43
  • 85
16
votes
2 answers

java.lang.IndexOutOfBoundsException: setSpan (-1 ... -1) starts before 0 at Android 8.0

The problem Since the upgrade to Android 8.0 I get many crash reports stating an IndexOutOfBoundsException that occurs outside my code.But different with the other question The crash report it seems to be a bug in Android itself.But I guess…
chenjian chen
  • 161
  • 1
  • 3
16
votes
3 answers

List Index Out of Range exception when creating a task

The exact error: Index was out of range. Must be non-negative and less than the size of the collection. I've index arrays and lists countless times. I've used for loops with arrays and lists countless times. The data is there, it works. Except…
16
votes
2 answers

Android Proguard Issue - Still getting "java.io.IOException: Can't process class..." error when obfuscation is skipped

I am building an android app with proguard in Android Studio and my project has a library jar (na.jar) that I would like to skip obfuscation and preverification because some classes from the na.jar are giving me errors during the build. So in my…
15
votes
4 answers

Difference between ArrayIndexOutOfBoundsException and IndexOutOfBoundsException?

What are the use cases in which we should use ArrayIndexOutOfBoundsException and `IndexOutOfBoundsException one over another?
quintin
  • 812
  • 1
  • 10
  • 35
14
votes
2 answers

how to resolve StringIndexOutOfBoundsException in android

This is my logcat report: java.lang.StringIndexOutOfBoundsException: length=0; regionStart=0; regionLength=2 at java.lang.String.startEndAndLength(String.java:583) at java.lang.String.substring(String.java:1464) at…
Farhan Shah
  • 2,344
  • 7
  • 28
  • 54
13
votes
3 answers

StaggeredGridLayoutManager calculateCachedStart() IndexOutOfBoundsException

Hi I got error report from Fabric on my apps -> IndexOutOfBoundsException on StaggeredGridLayoutManager calculateCachedStart() method There is many usage StaggeredGridLayoutManager on my apps. Any idea to fix this error or trace which one in my apps…
12
votes
2 answers

Android - java.lang.IndexOutOfBoundsException: Invalid item position 0(0). Item count:0

I am getting this exception in my log - java.lang.IndexOutOfBoundsException: Invalid item position 0(0). Item count:0 at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4622) at…
12
votes
6 answers

RecyclerView IndexOutOfBoundsException

Why exception execute when I removed some items in RecyclerView by using loop ? I used Collentions.synchronizedMap in adapter and 'deleteItem method' use synchronized too (the method in fragment). public void elementController(JsonObject jsonObject…
12
votes
6 answers

Why isn't the ArrayIndexOutOfBoundsException a compile time error?

Can someone explain to me why ArrayIndexOutOfBoundsException is a run-time exception instead of a compile-time error? In obvious cases when the indexes are negative or greater than the array size, I don't see why it cannot be a compile-time…
Laz London
  • 302
  • 1
  • 3
  • 11