Course contentsShow
← Java
Lesson 796 of 2,87019. Exception Hierarchy and Custom ExceptionsFree lesson

IndexOutOfBoundsException in Collections

Understand IndexOutOfBoundsException when accessing Lists and other indexed collections.

IndexOutOfBoundsException in Collections

What You'll Learn

You'll learn how IndexOutOfBoundsException occurs when accessing Lists and other indexed collections with invalid indices, and how it differs from array bounds checking.

The Core Concept

While arrays throw ArrayIndexOutOfBoundsException, indexed collections like ArrayList, LinkedList, and Vector throw the more general IndexOutOfBoundsException when you try to access elements at positions that don't exist.

This is an unchecked exception (a subclass of RuntimeException), meaning you're not required to catch it or declare it with throws. It signals a programming error—you've attempted to access an index that's out of the valid range.

Valid Index Range

For a collection with size() elements, valid indices are 0 through size() - 1. Anything outside this range triggers the exception:

List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
// Valid indices: 0, 1 (size is 2)

String first = names.get(0);     // OK
String invalid = names.get(5);   // IndexOutOfBoundsException!
String negative = names.get(-1); // IndexOutOfBoundsException!

Think of It Like This

Imagine a bookshelf with 5 books numbered 0–4. Asking for "book number 7" or "book number -2" doesn't make sense—those positions don't exist on your shelf. Java throws IndexOutOfBoundsException to tell you, "That position isn't available!"

Prevention

Always check the collection's size before accessing:

if (index >= 0 && index < names.size()) {
    String name = names.get(index);
}

Key Takeaway: IndexOutOfBoundsException is thrown when accessing indexed collections with invalid positions (negative or >= size), and it's an unchecked exception indicating a programming error that should be prevented with proper bounds checking.