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

Java string split with "." (dot)

Why does the second line of this code throw ArrayIndexOutOfBoundsException? String filename = "D:/some folder/001.docx"; String extensionRemoved = filename.split(".")[0]; While this works: String driveLetter = filename.split("/")[0]; I use Java 7.
Ali Ismayilov
  • 5,727
  • 2
  • 22
  • 24
390
votes
13 answers

Why doesn't list have safe "get" method like dictionary?

Why doesn't list have a safe "get" method like dictionary? >>> d = {'a':'b'} >>> d['a'] 'b' >>> d['c'] KeyError: 'c' >>> d.get('c', 'fail') 'fail' >>> l = [1] >>> l[10] IndexError: list index out of range
Mikhail M.
  • 5,588
  • 3
  • 23
  • 31
352
votes
17 answers

Initial size for the ArrayList

You can set the initial size for an ArrayList by doing ArrayList arr=new ArrayList(10); However, you can't do arr.add(5, 10); because it causes an out of bounds exception. What is the use of setting an initial size if you can't…
Cemre Mengü
  • 18,062
  • 27
  • 111
  • 169
341
votes
51 answers

RecyclerView: Inconsistency detected. Invalid item position

Our QA has detected a bug: when rotating the Android device (Droid Turbo), the following RecyclerView-related crash happened: java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid item position 2(offset:2).state:3 To me, it…
211
votes
8 answers

How do I get the first n characters of a string without checking the size or going out of bounds?

How do I get up to the first n characters of a string in Java without doing a size check first (inline is acceptable) or risking an IndexOutOfBoundsException?
antony.trupe
  • 10,640
  • 10
  • 57
  • 84
102
votes
8 answers

ArrayIndexOutOfBoundsException when using the ArrayList's iterator

Right now, I have a program containing a piece of code that looks like this: while (arrayList.iterator().hasNext()) { //value is equal to a String value if( arrayList.iterator().next().equals(value)) { // do something …
This 0ne Pr0grammer
  • 2,632
  • 14
  • 57
  • 81
80
votes
6 answers

java.lang.IndexOutOfBoundsException: Source does not fit in dest

On the following code: static void findSubsets (ArrayList numbers, int amount, int index) { ArrayList numbersCopy = new ArrayList(numbers.size()); Collections.copy(numbersCopy, numbers); } I'm getting the…
andandandand
  • 21,946
  • 60
  • 170
  • 271
60
votes
2 answers

How to initialize an empty ArrayList in Kotlin?

I have an empty arraylist: var mylist: ArrayList = ArrayList() When I want to set value in it I got this error: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0 The question is: How can I initialize my list?
SadeQ digitALLife
  • 1,403
  • 4
  • 16
  • 22
33
votes
13 answers

Java substring: 'String index out of range'

I guess I'm getting this error because the string is trying to substring a null value. But wouldn't the ".length() > 0" part eliminate that issue? Here is the Java snippet: if (itemdescription.length() > 0) { pstmt2.setString(3,…
phill
  • 13,434
  • 38
  • 105
  • 141
33
votes
2 answers

ArrayOutOfBoundsException on Bean creation while using Java 8 constructs

I am getting an ArrayIndexOutOfBoundsException on service start up (Bean creation) when i use Java 8 features. Java 8 has been set up and has been working. The code compiles correctly. On service start, the service fails to listen to port as the…
akshitBhatia
  • 1,131
  • 5
  • 12
  • 20
29
votes
3 answers

Why does IndexOutOfBoundsException now have a constructor with a long index as a parameter in Java 16?

I was checking the implementation of IndexOutOfBoundsException in JDK 16, and I have noticed that a new constructor with a long index has been introduced: /** * Constructs a new {@code IndexOutOfBoundsException} class with an * argument indicating…
M A
  • 71,713
  • 13
  • 134
  • 174
27
votes
7 answers

No out of bounds error

I have this code in C which takes in bunch of chars #include # define NEWLINE '\n' int main() { char c; char str[6]; int i = 0; while( ((c = getchar()) != NEWLINE)) { str[i] = c; ++i; printf("%d\n", i); } return…
Cemre Mengü
  • 18,062
  • 27
  • 111
  • 169
24
votes
2 answers

ArrayList.add throws ArrayIndexOutOfBoundsException

I am trying to add a object to a ArrayList and its throwing ArrayIndexOutOfBoundsException Following is the code private void populateInboxResultHolder(List inboxErrors){ inboxList = new ArrayList(); try{ …
mavrav
  • 550
  • 2
  • 6
  • 13
24
votes
6 answers

Insert at any position in java.util.List

According to the docs you can insert objects an any position in a List: The user of this interface has precise control over where in the list each element is inserted. (source: http://download.oracle.com/javase/6/docs/api/java/util/List.html) But…
fiskeben
  • 3,395
  • 4
  • 31
  • 35
21
votes
3 answers

ListView random IndexOutOfBoundsException on Froyo

I have an app with tons of downloads and I'm receiving a lot of this error: 16783 AndroidRuntime E java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0 16783 AndroidRuntime E at…
Draiken
  • 3,805
  • 2
  • 30
  • 48
1
2 3
99 100