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])
}