Skip to content
Exception in thread 'main' java.lang.ArrayIndexOutOfBoundsException

Exception in thread 'main' java.lang.ArrayIndexOutOfBoundsException

DodaTech 2 min read

ArrayIndexOutOfBoundsException fires when you access an array with an index outside 0 to length-1. You used a negative index or one >= the array length.

What It Means

Java arrays are zero-indexed. A valid index for an array of size N ranges from 0 to N-1. If you use index N or higher, or any negative index, the JVM throws this exception at runtime.

Why It Happens

  • Your loop condition uses <= instead of <.
  • You computed an index that falls outside the array range.
  • The array is empty (length 0) and you try to access index 0.
  • You used a hardcoded index that doesn’t match the actual array size.
  • You confused array length with the last valid index.

How to Fix It

1. Always validate the index before accessing

int[] numbers = {10, 20, 30};
int index = 3;

// Check before access
if (index >= 0 && index < numbers.length) {
    System.out.println(numbers[index]);
} else {
    System.out.println("Index out of bounds: " + index);
}

2. Fix loop bounds

// BUG: uses <= which goes one past the end
for (int i = 0; i <= numbers.length; i++) {
    System.out.println(numbers[i]);  // crash on last iteration
}

// FIX: use < instead of <=
for (int i = 0; i < numbers.length; i++) {
    System.out.println(numbers[i]);
}

3. Use length-1 for the last element

// Correct way to access the last element
int last = numbers[numbers.length - 1];

4. Handle empty arrays

public void printFirstElement(int[] arr) {
    if (arr == null || arr.length == 0) {
        System.out.println("Array is null or empty");
        return;
    }
    System.out.println("First element: " + arr[0]);
}

5. Use enhanced for-each when you don’t need the index

// Safer — no index at all
for (int num : numbers) {
    System.out.println(num);
}
Why does my ArrayList throw ArrayIndexOutOfBoundsException?
ArrayList throws IndexOutOfBoundsException with the message “Index: X, Size: Y” when you call get(X) and X >= size. Always check with list.size() before access, or use for (T item : list).
How do I safely get the last element of an array?
Always use arr[arr.length - 1], but first check that arr != null && arr.length > 0. A common mistake is using arr[arr.length] which will always throw the exception since indexing starts at 0.
What's the difference between length, length(), and size()?
array.length is a field for arrays. String.length() is a method for strings. list.size() is a method for collections. All three return the count of elements, and the last valid index is always count minus one.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro