06
Arrays
Concept
What is an Array?
- Stores multiple values of the same type
- Fixed size — cannot grow or shrink after creation
- Indices start at
0 - Arrays are objects — variables hold references
Syntax
Declaring & Instantiating
// Declare only int[] arr; // Declare + instantiate int[] arr = new int[10]; // Initialize with values int[] nums = {1, 2, 3, 4};
Syntax
Accessing & Updating Elements
// Access by index arr[0]; // first element arr[i]; // element at index i // Update an element arr[2] = 10; // Get the length arr.length; // property, NOT a method
⚠️ arr.length — no parentheses! It's a field, not a method call.
Traversal
Looping Through Arrays
// Standard for loop for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } // Enhanced for loop for (int value : arr) { System.out.println(value); }
Enhanced for loop can't modify elements or track the index. Use standard loop when you need
i.
Error
ArrayIndexOutOfBoundsException
Thrown when you access an index that doesn't exist.
int[] arr = new int[5]; arr[-1]; // ❌ index < 0 arr[5]; // ❌ index ≥ length arr[4]; // ✓ last valid index
Valid indices: 0 through arr.length - 1
Concept
Parallel Arrays
Two or more arrays storing related data at matching indices.
String[] names = {"Alice", "Bob", "Carl"}; int[] scores = {95, 87, 78}; // names[1] and scores[1] both refer to Bob
Concept
Array References & Aliasing
Array variables store references, not copies. Assigning one array variable to another creates an alias — both point to the same data.
int[] a = {1, 2, 3}; int[] b = a; // b aliases a! b[0] = 99; // a[0] is now 99 too!
This is a common AP exam trick. Changing
b changes a.
07
ArrayLists
Concept
What is an ArrayList?
- Resizable — grows and shrinks dynamically
- Part of the Java Collections Framework
- Cannot store primitives — must use wrapper classes
- Must import before use
import java.util.ArrayList;
Syntax
Declaring & Instantiating
// Declare ArrayList<Integer> nums; // Declare + instantiate ArrayList<Integer> nums = new ArrayList<Integer>(); // Diamond operator shorthand ArrayList<Integer> nums = new ArrayList<>();
Key Concept
Wrapper Classes
ArrayLists use object types, not primitives.
| Primitive | Wrapper |
|---|---|
| int | Integer |
| double | Double |
| boolean | Boolean |
| char | Character |
Java auto-boxes/unboxes:
list.add(5) works even though 5 is an int.
Methods
The 5 Core Methods
// Add to end list.add(value); // Add at specific index list.add(index, value); // Get element list.get(index); // Replace element list.set(index, value); // Remove element list.remove(index); // Size (method, not property!) list.size();
Traversal
Looping Through ArrayLists
// Standard for loop for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); } // Enhanced for loop for (Integer value : list) { System.out.println(value); }
⚠️ Exam Trap
Removing While Traversing
When you remove during a forward loop, indices shift left — you'll skip elements.
// ❌ WRONG — skips elements for (int i = 0; i < list.size(); i++) { if (list.get(i) == 0) list.remove(i); // bug! } // ✓ Fix 1: loop backward for (int i = list.size()-1; i >= 0; i--) { if (list.get(i) == 0) list.remove(i); } // ✓ Fix 2: decrement i after removal if (shouldRemove) { list.remove(i); i--; }
—
Algorithms
These are the most tested patterns on the AP exam. Know how to write each one for both arrays and ArrayLists.
Sum & Average
int[] arr = {3, 7, 2, 9, 1}; int sum = 0; for (int v : arr) sum += v; double avg = (double) sum / arr.length;
Find Maximum / Minimum
int max = arr[0]; // start with first element for (int i = 1; i < arr.length; i++) { if (arr[i] > max) max = arr[i]; } // For min: change > to <
Count Values Meeting a Condition
int count = 0; for (int v : arr) { if (v % 2 == 0) // condition: even count++; }
Search for a Value (Linear Search)
int target = 7; boolean found = false; for (int v : arr) { if (v == target) { found = true; break; } }
Replace Elements (Array)
// Replace all negatives with 0 for (int i = 0; i < arr.length; i++) { if (arr[i] < 0) arr[i] = 0; }
Replace Elements (ArrayList)
// Replace all negatives with 0 for (int i = 0; i < list.size(); i++) { if (list.get(i) < 0) list.set(i, 0); } // ⚠️ Can't use enhanced for to modify elements
Remove Elements Meeting a Condition (ArrayList only)
// Remove all negative numbers for (int i = list.size() - 1; i >= 0; i--) { if (list.get(i) < 0) list.remove(i); } // Backward loop = safe removal pattern
≠
Array vs ArrayList
| Feature | Array | ArrayList |
|---|---|---|
| Size | Fixed — set at creation | Dynamic — grows/shrinks |
| Import needed | No | Yes — java.util.ArrayList |
| Get size | arr.length (field) |
list.size() (method) |
| Access element | arr[i] |
list.get(i) |
| Update element | arr[i] = val |
list.set(i, val) |
| Add element | Not possible after creation | list.add(val) |
| Remove element | Not possible | list.remove(i) |
| Stores primitives | Yes — int, double, etc. |
No — must use wrappers |
| Performance | Faster (direct memory) | Slight overhead |
| Type declaration | int[] arr |
ArrayList<Integer> list |
✓
Study Checklist
0 / 20 complete
Define what an array is
Declare and instantiate an array
Initialize an array with values using
{}Access and update array elements
Use
arr.length correctly (no parentheses)Traverse with a standard for loop
Traverse with an enhanced for loop
Understand ArrayIndexOutOfBoundsException
Explain aliasing and array references
Understand parallel arrays
Import and declare an ArrayList
Know all 5 ArrayList methods
Understand wrapper classes
Traverse an ArrayList with both loop types
Safely remove elements while traversing
Write a sum/average algorithm
Write a max/min algorithm
Write a linear search algorithm
Write a replace elements algorithm
List 3+ key differences: Array vs ArrayList