Array — AP Computer Science A Study Guide
For: AP CS A candidates sitting AP Computer Science A.
Covers: Array declaration, instantiation, default values, indexing (0-based), traversal with standard
forand enhancedfor-each, common algorithms (sum, min/max, count, search, reverse), array as parameter — AP Computer Science A Unit 6.You should already know: Iteration (Unit 4), writing classes (Unit 5).
A note on the practice questions: All worked questions in the "Practice Questions" section below are original problems written by us in the AP Computer Science A style for educational use. They are not reproductions of past College Board papers.
1. Why Array Matters
Unit 6 is high yield — about 10-15% of the AP CS A score, and arrays underlie Unit 7 (ArrayList) and Unit 8 (2D Arrays). Most FRQ Question 3 and Question 4 are array-heavy.
Two foundational ideas:
- An array is a fixed-size, indexed collection of values of the same type.
- Arrays are reference types — variables hold pointers, not the contents directly.
2. Declaration and instantiation
int[] a; // declare a reference (currently null)
a = new int[5]; // instantiate length-5 array (default values: all 0)
int[] b = {3, 1, 4, 1, 5}; // declare + instantiate + initialize at once
String[] words = new String[3]; // String array (default values: all null)
Array length is fixed once allocated. To "grow", you must allocate a bigger array and copy.
Default values: int and double → 0 / 0.0; boolean → false; String and any reference type → null.
3. Indexing (0-based)
int[] a = {3, 1, 4, 1, 5};
a[0]; // 3
a[4]; // 5
a[5]; // ArrayIndexOutOfBoundsException at runtime
a.length; // 5 — note: NO parentheses (a field, not a method)
The last valid index is always a.length - 1. AP graders frequently check off-by-one errors.
You can read or write any valid index: a[2] = 99; updates the third element.
4. Traversal with standard for
int[] nums = {3, 1, 4, 1, 5};
int sum = 0;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
}
// sum = 14
Use this when you need the index (e.g. to compare adjacent elements, or to write to the array). The condition is i < nums.length, NOT <=.
5. Enhanced for-each loop
int[] nums = {3, 1, 4, 1, 5};
int sum = 0;
for (int n : nums) {
sum += n;
}
// sum = 14
Read it as "for each n in nums". Cleaner when you only need the value. Cannot use enhanced for to:
- Modify the array (
n = 99only changes the local copyn). - Get the index (use standard
forif you needi). - Iterate in reverse or skip elements.
6. Common algorithms
Find max:
int max = a[0];
for (int i = 1; i < a.length; i++) {
if (a[i] > max) max = a[i];
}
Linear search:
int target = 4;
int found = -1;
for (int i = 0; i < a.length; i++) {
if (a[i] == target) { found = i; break; }
}
Reverse in place (uses two-pointer):
for (int i = 0; i < a.length / 2; i++) {
int tmp = a[i];
a[i] = a[a.length - 1 - i];
a[a.length - 1 - i] = tmp;
}
Count occurrences:
int count = 0;
for (int n : a) {
if (n == target) count++;
}
7. Arrays as parameters and return types
public static int sum(int[] a) {
int total = 0;
for (int n : a) total += n;
return total;
}
public static int[] doubleAll(int[] a) {
int[] result = new int[a.length];
for (int i = 0; i < a.length; i++) result[i] = 2 * a[i];
return result;
}
When you pass an array to a method, the method gets a reference to the same array — modifications to elements inside the method are visible outside. (But reassigning the parameter to a new array doesn't affect the caller — only modifying contents does.)
8. Worked Example
Write a method mostFrequent(int[] arr) that returns the most frequent element. If there's a tie, return the smallest of the tied values.
Solution.
public static int mostFrequent(int[] arr) {
int bestVal = arr[0];
int bestCount = 0;
for (int i = 0; i < arr.length; i++) {
int count = 0;
for (int j = 0; j < arr.length; j++) {
if (arr[j] == arr[i]) count++;
}
if (count > bestCount || (count == bestCount && arr[i] < bestVal)) {
bestCount = count;
bestVal = arr[i];
}
}
return bestVal;
}
For each element arr[i], count its occurrences (inner loop), and update bestVal if this beats the current best (or matches but is smaller). — acceptable for AP-sized arrays.
For input {3, 1, 4, 1, 5, 1, 4, 4}: counts are 3→1, 1→3, 4→3, 5→1. Tied at 3 between 1 and 4 → return min = 1.
9. Common Pitfalls
lengthvslength(): array usesa.length(a field). String usess.length()(a method). The CED constantly tests this distinction.- Off-by-one: condition is
i < a.length, noti <= a.length. The last valid index isa.length - 1. - Modifying in enhanced for:
for (int n : a) n = 99;does not change the array —nis a copy of the value. - Forgetting
new:int[] a;declares but doesn't instantiate. Usinga[0]beforea = new int[5];causesNullPointerException. - Aliasing:
int[] b = a;makesbandapoint to the same array. To clone useArrays.copyOf(a, a.length).
10. Practice Questions (CED Style)
- Write a method
boolean isSorted(int[] a)returning true ifais in non-decreasing order, false otherwise. - Write a method
int[] removeDuplicates(int[] a)returning a new array with consecutive duplicates removed (e.g. {1,1,2,3,3,3,4} → {1,2,3,4}). - Given
int[] a = {5, 3, 8, 1, 4}, write code that swaps the largest and smallest elements without using a separate sort step.
11. Quick Reference Cheatsheet
- Declaration:
int[] a = new int[10];orint[] a = {1,2,3}; - Index 0-based: last index
a.length - 1. - Length:
a.length(no parentheses). - For loop:
for (int i = 0; i < a.length; i++)— for index access. - For-each:
for (int n : a)— for value-only read. - Defaults: int=0, double=0.0, boolean=false, reference=null.
- Pass by reference: methods see the same array.
- Out-of-bounds:
a[a.length]throwsArrayIndexOutOfBoundsException.
12. What's Next
Array is the foundation for Unit 7 (ArrayList) — variable-length, more methods. Unit 8 (2D Arrays) extends to grid/matrix. Practice writing array algorithms by hand; AP FRQ Question 3 is guaranteed to be array or ArrayList. Use Ollie to walk through any specific algorithm: "How do I find the second-largest element in O(n)?" or "Help me trace this nested-loop array problem."