Unit 6: Array
AP Computer Science A: 51 practice questions with detailed explanations.
Unit Study Guide
Executive Summary
Arrays store many values of one type in a fixed-size, indexed structure. Indexes run 0 to length - 1.
Creating and accessing
int[] a = new int[n] creates n zeros. Access with a[i]; the length is a.length (a field, not a method). Indexing past the end throws ArrayIndexOutOfBoundsException at runtime, not compile time.
Traversals
Use for (int i = 0; i < a.length; i++) for full access to indexes. The enhanced for (int x : a) reads values only — x is a copy, so assigning to it does not change the array.
Common algorithms
Sum with an accumulator. Find max by tracking the largest value (and its index). Count matches with a counter. Reverse by swapping mirror pairs through the middle. Search linearly with a flag or early return; return -1 when not found.
Aliasing
After int[] b = a, both names point to the same array — changing b[0] changes a[0]. To copy values, loop them over.
Exam traps
The last index is a.length - 1. A loop with i ≤ a.length crashes on the final iteration. Enhanced for loops cannot modify elements or traverse in reverse.