Why this speed sheet belongs in your back pocket
Studying for AP Computer Science A (CSA) often feels like learning a new language under a stopwatch. That’s exactly why a tight, practical speed sheet for core Java constructs — especially loops, arrays, and ArrayList — will save you time on exams and projects. This guide is written for students: conversational, example-rich, and full of the little reminders that make syntax stick. Treat this as a cheat-code for clarity (but not a shortcut for practice!).
How to use this guide
Read the quick-reference table first when you want the facts fast. Then work through the annotated examples to understand why each construct behaves the way it does. Use the practice prompts at the end to convert knowledge into speed. If you prefer one-on-one walkthroughs, Sparkl’s personalized tutoring can help you build a tailored study plan and give targeted feedback on timed practice — ideal for students aiming to boost both correctness and pace.
Fundamental building blocks: variables and control flow recap
Before loops and collections get interesting, make sure these basics are second-nature: variable declaration, simple if/else, and method signatures. In AP CSA context, you’ll see signatures like public int sum(int[] nums)
or public static void main(String[] args)
. Get comfortable with types, return values, and array references — they determine how loops and collections behave.
Quick reminders
- Primitive types (int, double, boolean) store values. Objects (String, Integer, ArrayList<Integer>) store references.
- Arrays have fixed length once created:
int[] a = new int;
- ArrayList grows and shrinks:
ArrayList<Integer> list = new ArrayList<>();
Loops: for, enhanced for (for-each), while, and do-while
Loops are about repetition — but each loop fits certain situations better. Below is how to think about them and snapshot syntax you can memorize.
1) Classic for loop — index control
Best when you need the index (i) to access or modify an array or to step in custom increments.
Syntax pattern:
for (int i = 0; i < N; i++) {
// use i and array[i]
}
Example — sum of array elements:
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
Common pitfall: off-by-one. Remember arrays are 0-indexed; last index is arr.length - 1
.
2) Enhanced for loop (for-each) — cleaner reading
Best when you only need each element and not the index.
for (int val : arr) {
// use val
}
Example — print each element:
for (int v : arr) {
System.out.println(v);
}
Note: This works with arrays and any Iterable (like ArrayList). You cannot modify the array length or the collection structure inside this loop safely.
3) while loop — condition-first repeat
Use when the number of iterations isn’t known upfront and you want to check a condition before each iteration.
while (condition) {
// repeated work
}
Example — iterate until a sentinel value is found:
int i = 0;
while (i < arr.length && arr[i] != -1) {
// process arr[i]
i++;
}
4) do-while — run at least once
When you must execute the body at least once, then test a condition.
do {
// run at least once
} while (condition);
Example — prompt until valid input found (pseudocode):
String s;
do {
s = readLine();
} while (!isValid(s));
Arrays: declaration, common operations, and patterns
Arrays are the foundation of many CSA problems: fixed-size, fast, and simple. Master these operations and you’ll handle most array-based questions in your sleep.
Declaration and initialization
- Declare without size:
int[] nums;
- Create with size:
nums = new int;
- Declare and fill:
int[] primes = {2, 3, 5, 7};
Access and length
Access: nums[i]
. Length: nums.length
(no parentheses).
Copying arrays
Shallow copy of reference: int[] b = a;
(both refer to same array). To copy values, use a loop or Arrays.copyOf
(AP environment may favor loops):
int[] copy = new int[a.length];
for (int i = 0; i < a.length; i++) {
copy[i] = a[i];
}
Common array patterns
- Find max/min: loop and compare.
- Reverse in-place: swap symmetrical indices.
- Shift elements: for loops with new index mapping.
- Count occurrences / frequency tables: use extra arrays when range is small.
ArrayList: dynamic, flexible, and often easier
ArrayList is part of java.util and behaves like a resizable array. It’s a go-to when the size isn’t fixed or you need convenient add/remove operations.
Declaration patterns
ArrayList<Integer> list = new ArrayList<>();
ArrayList<String> people = new ArrayList<>(initialCapacity);
Use wrapper types (Integer, Double) for primitives in generics.
Essential methods
add(E e)
— append to endadd(int index, E e)
— insert at indexget(int index)
— reads elementset(int index, E e)
— replace elementremove(int index)
— remove by indexremove(Object o)
— remove by value (first match)size()
— number of elementsisEmpty()
— true if size is zero
Iterating an ArrayList
Same loop types apply. When modifying structure (add/remove), prefer index-based for loops or iterate carefully with indices adjusted.
for (int i = 0; i < list.size(); i++) {
Integer v = list.get(i);
}
Be careful: calling list.remove(i)
shifts subsequent elements left, so decrement or avoid skipping elements.
Head-to-head: Array vs ArrayList
Quick conceptual comparison helps you choose the correct structure during the exam.
Characteristic | Array | ArrayList |
---|---|---|
Size | Fixed after creation | Dynamic, grows/shrinks |
Syntax | int[] a = new int[n]; |
ArrayList<Integer> a = new ArrayList<>(); |
Performance | Fast index access; lower overhead | Fast index access; add/remove have overhead when shifting |
Use case | When size known or performance-critical | When size varies or convenience needed |
Annotated examples — short problems solved step-by-step
Example 1: Remove duplicates from an array (preserve order)
Idea: Use an ArrayList to build output by testing membership. This demonstrates interplay between arrays and ArrayList.
public int[] removeDuplicates(int[] arr) {
ArrayList<Integer> out = new ArrayList<>();
for (int v : arr) {
if (!out.contains(v)) { // O(n) contains makes this O(n^2) worst-case
out.add(v);
}
}
// convert back to array
int[] res = new int[out.size()];
for (int i = 0; i < out.size(); i++) res[i] = out.get(i);
return res;
}
Note: For CSA problems, this is acceptable unless constraints explicitly require better complexity. If needed, mention trade-offs and optimize with other techniques.
Example 2: Shift array right by k positions (in-place)
Approach: Reverse segments. This is a classic pattern that shows index math and use of loops.
public void rotateRight(int[] arr, int k) {
int n = arr.length;
k = k % n;
reverse(arr, 0, n - 1);
reverse(arr, 0, k - 1);
reverse(arr, k, n - 1);
}
private void reverse(int[] a, int i, int j) {
while (i < j) {
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
i++; j--;
}
}
Example 3: Safely remove all negative numbers from an ArrayList<Integer>
When removing while iterating, handle index shifts properly.
for (int i = 0; i < list.size(); i++) {
if (list.get(i) < 0) {
list.remove(i);
i--; // step back to avoid skipping
}
}
Alternative: iterate from end to start to avoid index adjustments.
Common pitfalls and exam-safe patterns
- Off-by-one errors with loops: always check last index as
length - 1
. - Modifying a collection during a for-each loop: avoid this; use index-based loop instead.
- Null and empty checks:
if (arr == null || arr.length == 0) return ...;
- Remember wrapper types for collections:
ArrayList<Integer>
, notArrayList<int>
. - Use descriptive variable names in practice; abbreviations cost time when debugging under pressure.
Speed patterns you can memorize
These patterns frequently appear on CSA exams and are worth practicing until they’re reflexive.
- Reverse array in-place: two-pointer swap pattern.
- Count frequency with an array when values are small in range.
- Use
size()
for ArrayList bounds;length
for arrays. - When removing items while iterating, loop backward:
for (int i = list.size()-1; i >= 0; i--)
. - For scanning an array and building another, prefer new array allocation if final size is known; otherwise, use ArrayList then convert.
Practice prompts (timed)
Try to solve each prompt in 8–12 minutes, then refine for correctness and efficiency. Time yourself — build speed and accuracy together.
- Write a method to return the second largest value in an int[] (assume length >= 2).
- Given an ArrayList<String>, remove all strings that contain the letter ‘a’ (case insensitive).
- Merge two sorted int[] arrays into one sorted array.
- Given int[] arr, return an ArrayList<Integer> of prefix sums (running totals).
Study plan: turning this sheet into exam performance
Follow a repeating 3-step loop each study session: Learn → Apply → Review.
- Learn: Read a focused section of this sheet (e.g., ArrayList methods) and write 3-5 short examples by hand.
- Apply: Do 2 timed practice prompts that use those constructs. Simulate exam constraints (no internet, only allowed notes).
- Review: Go over mistakes immediately. If you repeatedly miss a pattern, build flashcards or a micro-drill. Sparkl’s personalized tutoring can speed this review cycle by providing 1-on-1 guidance and AI-driven insights that pinpoint weak patterns and set a tailored practice plan.
Cheat-sheet table — memorize these lines
Concept | Common Syntax | When To Use |
---|---|---|
For loop | for(int i=0;i<N;i++) |
When you need the index or custom stepping |
Enhanced For | for(Type x : arr) |
Read-only iteration over array/collection |
While | while(condition) |
Unknown iterations, condition-first |
Do-While | do{ }while(cond); |
Run body at least once |
Array | int[] a = new int[n]; |
Fixed size, primitive storage |
ArrayList | ArrayList<T> list = new ArrayList<>(); |
Variable size, use wrapper types |
Exam-day checklist
- Read each prompt fully; identify input/output types first.
- Sketch a short plan: which loops, arrays, or ArrayList methods are needed?
- Write code in small, testable chunks. If you’re unsure, write comments for intended logic then fill in loops.
- Keep an eye on off-by-one and null checks.
- Use simple variable names during the exam; clarity beats cleverness under time pressure.
When to call for extra help
If you find mistakes are repeating — for instance, mixing up size()
and length
, or consistently making index errors — targeted coaching accelerates improvement. Sparkl’s personalized tutoring offers expert tutors who create a tailored plan, walk through common pitfalls, and use AI-driven insights to measure progress so your practice becomes smarter, not just longer.
Final tips — mindset and micro-habits
- Practice daily in short bursts (30–60 minutes). Consistency beats marathon cramming.
- After each practice session, write a 2-line summary: what you learned, and one mistake to fix next time.
- Read others’ short solutions to CS problems to learn different loop/array patterns.
- Keep this speed sheet handy and rewrite it by hand once a week — the act of writing makes syntax stick.
Wrap-up: from confusion to fluency
Loops, arrays, and ArrayList are the workhorses of AP CSA. The goal isn’t to memorize every possible trick; it’s to develop reliable patterns: choose the right loop, manage indices carefully, and prefer ArrayList when size variability matters. Practice these patterns until they’re automatic. If you want faster progress, combine disciplined practice with targeted feedback — for example, Sparkl’s personalized tutoring pairs one-on-one guidance with tailored study plans to help you convert practice into points on the exam.
Keep this sheet as a living document: add the snippets you write during practice, note the errors you make most often, and revisit the cheat-sheet table before any timed run. With steady practice and the right guidance, you’ll not only know the syntax — you’ll move through problems with speed and confidence.
Good luck — and enjoy the elegant logic of Java. You’ve got this.
No Comments
Leave a comment Cancel