Java Reference ยท java.lang
IndexOutOfBoundsException
Reference for IndexOutOfBoundsException and its subclasses ArrayIndexOutOfBoundsException and StringIndexOutOfBoundsException: messages, causes and prevention.
IndexOutOfBoundsException is thrown when an index (a position) is outside the valid range of an ordered structure: a list, a string, an array or a similar sequence. Valid indexes run from 0 to size - 1, so asking for position size or a negative position fails. It extends RuntimeException.
Two subclasses cover the most common cases: ArrayIndexOutOfBoundsException for arrays and StringIndexOutOfBoundsException for String, StringBuilder and friends. Lists throw the base class itself.
int[] a = new int[3]; a[3] = 1; // ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
public class IndexOutOfBoundsException extends RuntimeException
| Constructor | Description |
|---|---|
IndexOutOfBoundsException() |
No message. |
IndexOutOfBoundsException(String message) |
Detail message. |
IndexOutOfBoundsException(int index) |
Message Index out of range: index (since Java 9). |
IndexOutOfBoundsException(long index) |
Same, for long indexes (since Java 16). |
| Subclass | Thrown by |
|---|---|
ArrayIndexOutOfBoundsException |
Array access with an invalid index. |
StringIndexOutOfBoundsException |
charAt, substring, StringBuilder operations and similar. |
Usage notes
- Valid range is
0tolength - 1. The last element islength - 1; most off-by-one bugs come from using<=or from forgetting the 0-based start. - Message formats in current JDKs read
Index 3 out of bounds for length 3;substringsaysRange [2, 9) out of bounds for length 5, andArrayList.add(index, e)still uses the olderIndex: 5, Size: 2. Treat the exact wording as unstable and do not parse it. add(index, e)allowsindex == size(append) butget,setandremovedo not.- Empty collections have no valid index at all:
list.get(0)on an empty list fails, so testisEmpty()first. - Ranges end exclusively in
substring(begin, end)andsubList(from, to);endmay equal the length,beginmay not exceedend. - Concurrent changes. A list can shrink between your size check and your
get; guard shared lists with a lock or use a thread-safe structure. Objects.checkIndex(index, length)(Java 9+) is the standard helper for validating indexes in your own collections.NoSuchElementExceptionis thrown instead for empty queues andOptional.get(), andNegativeArraySizeExceptionfornew int[-1].