Unit 2 Cycle 2 Day 21
Share
Practice Question
int[] arr = {5, 10, 15, 20, 25};
for (int i = 0; i <= arr.length; i++) {
System.out.println(arr[i]);
}
The correct answer is C) The code causes an ArrayIndexOutOfBoundsException
This is a classic off-by-one error. The array has 5 elements with valid indices 0, 1, 2, 3, 4.
The loop condition i <= arr.length is WRONG because:
- arr.length = 5
- The loop runs with i = 0, 1, 2, 3, 4, and then 5
- When i = 5, the code tries to access arr[5], which doesn't exist
- This throws an ArrayIndexOutOfBoundsException
The correct loop condition should be: i < arr.length (without the equals sign)
A) Prints all 5 elements correctly - This would require the condition i < arr.length, not i <= arr.length.
B) Prints only the first 4 elements - This would happen if the condition was i < arr.length - 1, which would stop at index 3.
D) Prints 6 elements including duplicate - Arrays have fixed size and cannot print elements that don't exist without throwing an exception.
Off-by-one errors are one of the most common bugs in programming. Remember: array indices go from 0 to length-1, NOT 0 to length. The loop condition should almost always be i < arr.length, not i <= arr.length. The exception is when you're working with 1-indexed counting (like row numbers), not array indices.
On the AP exam, carefully check loop bounds when working with arrays. A common trap is using <= when you should use <. If you see arr.length in a loop condition, immediately verify whether the code will try to access an invalid index. Array indices are ALWAYS 0 to length-1.
Keep Practicing!
Cycle 2 questions prepare you for the hardest AP CSA exam questions.
Study Games Practice FRQs