Index Out of Bounds / IndexError — Java, Python & C# Fix Guide
What Does This Error Mean?
You tried to access an array/list element at a position that doesn't exist. Arrays are zero-indexed, so an array of length 5 has valid indices 0–4. Accessing index 5 (or -1) throws this error.
Error Names by Language
- Java: ArrayIndexOutOfBoundsException / IndexOutOfBoundsException
- Python: IndexError: list index out of range
- C#: IndexOutOfRangeException
- JavaScript: Returns undefined (no error!) — which causes TypeErrors later
Common Causes
- Off-by-one error in a loop:
for (i = 0; i <= arr.length; i++)should be< - Empty array/collection: accessing [0] when list is empty
- Assuming data exists: API returned fewer items than expected
How to Fix It
1. Check length before access
// Java
if (index >= 0 && index < list.size()) {
return list.get(index);
}
# Python
if 0 <= index < len(my_list):
return my_list[index]2. Fix loop boundaries
// Wrong: i <= length (accesses one past end)
for (int i = 0; i < arr.length; i++) { ... }3. Use safe access patterns
# Python: use .get() or slicing
value = my_list[index] if index < len(my_list) else default
// Java: Optional pattern
Optional.ofNullable(list.size() > i ? list.get(i) : null)