Out-of-Bounds Errors

Part of: Array

The Most Common Array Bug. When you access an index that does not exist, Java throws an ArrayIndexOutOfBoundsException at runtime. This is the single most common array error, and the AP exam tests your ability to spot it. Valid Index Range. For an array of length n, the only legal indices are 0 through n - 1. Any of these throws the exception: Both too-high and negative indices are illegal. Off-by-One Errors in Loops. Most out-of-bounds bugs come from a loop condition that is off by one: The fix is using < instead of <=. Remember: the last valid index is a.length - 1, never a.length. Empty Arrays. An array of length 0 has no valid indices at all . Accessing a[0] on it throws the exception. Code that assumes at least one element (like int max = a[0];) will crash on an empty array, so guard against it when input size could be zero: Looking Ahead Safely. Algorithms that compare a[i] with a[i + 1] must stop one early so i + 1 stays in bounds: What usually goes wrong. What you see What caused it How to fix it --- --- --- Index 3 out of bounds for length 3 The loop ran while i <= a.length, so it read one slot past the end Use i < a.length A crash only on the final comparison of a look-ah

Challenge: Count Adjacent Equal Pairs