Bugs
Java ArrayIndexOutOfBoundsException: Causes and Fixes
AIOOBE is thrown when code accesses an array index that is negative or >= the array's length. It is almost always an off-by-one error.
❌ Off-by-One Error
public void processScores(int[] scores) {
for (int i = 0; i <= scores.length; i++) { // Bug: should be <
System.out.println(scores[i]); // Throws when i == scores.length
}
}✅ Correct Loop
public void processScores(int[] scores) {
for (int i = 0; i < scores.length; i++) {
System.out.println(scores[i]);
}
// Or the enhanced for-loop (no index arithmetic):
for (int score : scores) {
System.out.println(score);
}
}💡
Pro tip: Prefer the enhanced for-loop when you don't need the index. It eliminates index arithmetic entirely and cannot produce AIOOBE.
Paste this code into LearnCodeGuide
Detect Java vulnerabilities and bugs automatically with AI-powered analysis.
Analyze Java Code →