Unit 4 Cycle 1 Day 3: Array Out of Bounds
Share
Array Out of Bounds
Section 4.1 — Array Creation and Access
Key Concept
An ArrayIndexOutOfBoundsException occurs at runtime when code attempts to access an index less than 0 or greater than or equal to the array's length. This is a runtime error, not a compile error — the code compiles but crashes when it runs. Common causes include: using <= instead of < in a loop condition, starting at index 1 instead of 0, or accessing arr[arr.length] instead of arr[arr.length - 1]. The AP exam frequently tests off-by-one errors that cause this exception.
Consider the following code segment.
What happens when this code executes?
Answer: (C) An ArrayIndexOutOfBoundsException occurs.
The array has 3 elements at indices 0, 1, 2. Index 3 is out of bounds. Java throws an ArrayIndexOutOfBoundsException at runtime.
Why Not the Others?
(A) Accessing beyond the array does not return null. It throws an exception.
(B) "Jo" is at index 2, the last valid index.
(D) The code compiles. The error occurs at runtime when the invalid index is accessed.
Common Mistake
Array bounds are checked at runtime, not compile time. The compiler cannot detect that index 3 is invalid for a 3-element array.
AP Exam Tip
ArrayIndexOutOfBoundsException is a RUNTIME error. Valid indices for an array of size n are 0 through n-1. Index n is always out of bounds.