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

index out of bounds exception java

So the error message is this: Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 at java.util.ArrayList.rangeCheck(Unknown Source) at java.util.ArrayList.get(Unknown Source) at…
5
votes
1 answer

notifyDataSetChanged() - IndexOutOfBoundException

I do not understand what is wrong I am use public class UrlArrayAdapter extends BaseAdapter {... ArrayList objects; UrlArrayAdapter(Context context, ListView urlListView, ArrayList
Max Usanin
  • 2,479
  • 6
  • 40
  • 70
5
votes
1 answer

java.lang.StringIndexOutOfBoundsException: index=0 length=0 in get sqlite database

I am trying to open a writeable SQLite database with this code... public DataAdapterForServieClass open() throws SQLException { db = DBHelper.getWritableDatabase(); return this; } However I am getting the following error on the db =…
Kishor datta gupta
  • 1,103
  • 2
  • 14
  • 42
4
votes
1 answer

IndexOutOfBoundsException in ViewTreeObserver

Since several months I experience IndexOutOfBoundsExceptions in Crashlytics and Google Play Console. I cannot figure out where exactly it happens, as the stack trace only lists framework code (see stack trace below). From the firebase events I guess…
Aorlinn
  • 718
  • 5
  • 16
4
votes
2 answers

Converting a captured image to a Bitmap

I'm exploring CameraX API of android using Java and trying to build capture image use-case. Here is the code for private void takePicture() { imageCapture.takePicture(new ImageCapture.OnImageCapturedListener() { @Override …
4
votes
1 answer

Is having two versions of the same method which only differ in their signature (method name and 'throws' attribute) considered bad design?

I would like to design an API where I have two versions of the same method, extractLastElement(): First version will not have a throws attribute: Object extractLastElementSafe(); Will be used when the client 'knows for sure' there are elements…
4
votes
2 answers

Java String Index Out Of Bounds Exception

Yes I know how to fix this. I was looking at the API between String Class and String Builder Class. Here's what I question: StringBuilder sb = new StringBuilder("wibble"); String s = new String("wobble"); sb.charAt(index) //Can throw Index Out Of…
4
votes
1 answer

RecyclerView: Inconsistency detected when update grouped items by PagedListAdapter

I using android.arch.paging.PagedListAdapter and Room DB as data source for show items in RecyclerView. Each item has date day. I also group elements by this date in override fun onCurrentListChanged(currentList:…
4
votes
2 answers

Xamarin Form: ListView causing Specified argument was out of the range of valid values. Parameter name: index

I have tried a lot of combination to test the code in LoadData function. The first time the Page loaded, the LoadData function got called. Later user change the date which causing the LoadData function to be called again. This time there was an…
LittleFunny
  • 8,155
  • 15
  • 87
  • 198
4
votes
5 answers

index out of bounds c# (I'm trying to add savegame and am using WriteAllLines)

I am trying to make savegame for a quite simple game, and this is the code I am using right now to write money to a .txt file (NameBox is the textbox you use to write the name of the .txt file): private void SaveBtn_Click(object sender, EventArgs…
jomoetnt
  • 51
  • 4
4
votes
1 answer

Android: Snackbar gives ArrayIndexOutOfBoundsException

the code that seems to give the exception is the following: Snackbar.make(findViewById(R.id.content_main), "E' necessario abilitare il GPS per aggiornare la lista", Snackbar.LENGTH_INDEFINITE) .setAction("ATTIVA", new View.OnClickListener()…
DomeWTF
  • 2,342
  • 4
  • 33
  • 46
4
votes
4 answers

I need string that starts with number from my input string

Here is my code String itemName = "Daily 60k tube"; String name=""; if(itemName.matches(".*\\d+.*")) { itemName = itemName.substring(itemName.indexOf(" ") + 1); itemName = itemName.substring(0, itemName.indexOf("…
user3427729
4
votes
0 answers

Android - Index Out Of Bounds On Tablet Only?

This makes no sense to me, I am getting an index out of bounds exception from some code that fetches and splits a response from the server to determine a users account details and account type. Crash Report (Reason): 07-06 12:11:30.602…
Luke Swain
  • 223
  • 2
  • 7
4
votes
1 answer

AppBarLayout: how to removeOnOffsetChangedListener

In order to detect finish of app bar collapsing I called addOnOffsetChangedListener. In listener's onOffsetChanged I catch and handle the moment of collapsing done. Then I need to stop listen for offset changes. In most examples here is call of…
Alexey
  • 2,980
  • 4
  • 30
  • 53
4
votes
7 answers

Converting to binary - getting IndexOutOfBoundsException

Below is some code I'm working on, I thought I'd make myself a binary calculator to make my life slightly easier. However, when I run it, I get an error telling me that there is a Java.lang.StringIndexOutofBoundsException. I don't really know how to…
arsb48
  • 563
  • 4
  • 10