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);
}Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro