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: Using a.length - 1 keeps the look-ahead a[i + 1] from ever exceeding the last index.

Challenge: Count Adjacent Equal Pairs