Ad Space — Top Banner

IndexOutOfBoundsException

Java Programming Language

Severity: Moderate

What Does This Error Mean?

IndexOutOfBoundsException means you tried to access a position in a list that doesn't exist. For example, reading index 5 from a list that only has 3 items. Java throws this to prevent reading random memory.

Affected Models

  • Java 8
  • Java 11
  • Java 17
  • Java 21
  • Android (Java/Kotlin)

Common Causes

  • Accessing a list index equal to or greater than list.size()
  • Using a negative index on a List or ArrayList
  • Off-by-one error in a loop — iterating one step too many
  • List was modified (items removed) while iterating, shrinking it unexpectedly
  • Hardcoding an index without checking if the list is large enough

How to Fix It

  1. Check the index you are using against list.size().

    Valid indexes run from 0 to list.size() - 1. Index equal to size() is always out of bounds.

  2. Guard the access with an if-check before reading the index.

    Example: if (index >= 0 and index < myList.size()) { ... }

  3. Review any loop that iterates over the list.

    Use i < list.size() as the loop condition, not i <= list.size().

  4. Use an enhanced for-each loop when you only need values, not indexes.

    for (String item : myList) avoids manual index management entirely.

  5. If you remove items inside a loop, iterate in reverse or use an Iterator.

    Removing forward while iterating shifts indexes and causes this exception.

When to Call a Professional

This is a coding bug, not a hardware issue. If it appears in production code you did not write, escalate to your development team.

Frequently Asked Questions

What is the difference between IndexOutOfBoundsException and ArrayIndexOutOfBoundsException?

ArrayIndexOutOfBoundsException is specifically for arrays. IndexOutOfBoundsException covers Lists, ArrayLists, and other collections. Both mean you accessed an invalid position.

Why does Java use 0-based indexing?

Java follows the C tradition where index 0 means 'start of the block of memory'. This is just how most languages work — the first item is always at index 0.

How do I safely get the last element of a list?

Use list.get(list.size() - 1) to get the last item. Always check that list.size() > 0 first to avoid the exception on an empty list.