🔧 Error Fixes
· 2 min read

IndexOutOfBoundsException — How to Fix It


java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
System.IndexOutOfRangeException: Index was outside the bounds of the array
panic: runtime error: index out of range [5] with length 5

You’re trying to access an element at an index that doesn’t exist. Arrays are zero-indexed — an array of length 5 has indices 0-4, not 1-5.

Fix 1: Off-by-One Error

// ❌ Using <= instead of <
String[] names = {"Alice", "Bob", "Charlie"};
for (int i = 0; i <= names.length; i++) {  // 💥 Fails at i=3
    System.out.println(names[i]);
}

// ✅ Use < (not <=)
for (int i = 0; i < names.length; i++) {
    System.out.println(names[i]);
}

Fix 2: Empty Collection

// ❌ Accessing first element of empty list
List<String> items = new ArrayList<>();
String first = items.get(0);  // 💥 IndexOutOfBoundsException

// ✅ Check size first
if (!items.isEmpty()) {
    String first = items.get(0);
}

Fix 3: Hardcoded Index

// ❌ Assuming the array has at least 3 elements
string name = args[2];  // 💥 If fewer than 3 args

// ✅ Check length first
if (args.Length > 2) {
    string name = args[2];
}

Fix 4: Wrong Loop Variable

// ❌ Using wrong array's length
String[] names = {"Alice", "Bob"};
int[] scores = {90, 85, 78, 92};

for (int i = 0; i < scores.length; i++) {
    System.out.println(names[i]);  // 💥 names only has 2 elements
}

// ✅ Use the correct length
for (int i = 0; i < names.length; i++) {
    System.out.println(names[i] + ": " + scores[i]);
}

Fix 5: Substring Out of Range

// ❌ Substring beyond string length
String text = "Hello";
String sub = text.substring(0, 10);  // 💥 StringIndexOutOfBoundsException

// ✅ Clamp to string length
String sub = text.substring(0, Math.min(10, text.length()));

Fix 6: Go Slice Bounds

// ❌ Slicing beyond length
s := []int{1, 2, 3}
fmt.Println(s[5])  // 💥 panic: index out of range

// ✅ Check bounds
if len(s) > 5 {
    fmt.Println(s[5])
}