AP Computer Science A — Cheatsheet
Formulas, exam-day tips, and key terms on one page.
Formulas & relationships
Constructing and using an object
ClassName ref = new ClassName(args); ref.method(args);
`new` builds the object and returns a reference; dot notation then sends messages to it.
substring(from, to)
s.substring(a, b) → characters at indices a through b − 1
The start index is included, the end index is excluded, so the result has length b − a. `s.substring(a)` alone returns from index a to the end.
indexOf
s.indexOf(t) → first index where t begins, or −1 if absent
Searching left to right, it reports the position of the first match. A return of −1 means the substring is not present.
Integer vs. double division
7 / 2 = 3 (int) 7.0 / 2 = 3.5 (double)
If both operands are int, the result is truncated to an int. One double operand promotes the whole operation to double.
Truth of && and ||
a && b : true only if both true · a || b : true if either true
`!a` reverses a. Short-circuiting means the right operand may be skipped once the result is settled.
for loop header
for (init; test; update) { body }
init runs once; test is checked before each iteration; body then runs; update runs after the body; repeat until test is false.
Total inner executions (fixed bounds)
outer passes × inner passes = total inner-body runs
When the inner bound depends on the outer variable, add up the per-pass counts instead of multiplying.
Three-step swap
temp = a; a = b; b = temp;
The temporary variable preserves the first value so it is not lost when the second is copied in.
A minimal class
class C { private T field; C(T v){ field = v; } T getField(){ return field; } }
Instance variable + constructor + accessor is the core shape of nearly every AP class.
this to resolve shadowing
public Point(int x) { this.x = x; }
`this.x` is the instance variable; the bare `x` is the parameter. `this` picks the field when the names collide.
Encapsulation pattern
private field + public getter/setter = controlled access
Data is hidden; all reads and writes flow through methods the class controls.
Subclass with super call
class Sub extends Super { Sub(){ super(args); } }
`super(args)` runs the superclass constructor first, initializing inherited fields before the subclass adds its own setup.
Array length and last index
valid indices: 0 … arr.length − 1
`arr.length` is a field (no parentheses). The last usable index is one less than the length.
ArrayList essentials
list.add(x) list.get(i) list.size() list.remove(i)
Zero-based indexing. `remove(i)` deletes index i and shifts later elements left, shrinking size by 1.
2D array dimensions
rows = m.length columns = m[0].length
Access is m[row][col], both zero-based. new int[R][C] has R rows and C columns.
Find the maximum
int max = a[0]; for (int i = 1; i < a.length; i++) if (a[i] > max) max = a[i];
Seed max with the first element, then update it whenever a larger element appears. One pass finds the maximum.
On the exam
- On the exam, `new` always appears with a class that has a matching constructor. If the arguments do not match any constructor’s parameter list, the code fails to compile — check the number and types of arguments carefully.
- When you see chained calls, rewrite them as separate steps on scratch paper: compute the leftmost call, replace it with its result, and repeat. This prevents mis-reading `s.trim().length()` as calling `length()` on the original spaced string.
- For any `indexOf` or `substring` question, write the string out and label each character with its index starting at 0. Counting on paper prevents off-by-one mistakes with the excluded end index.
- `Math` methods are static: always call them as `Math.name(...)`, never on an object. And watch the return type — `Math.pow` returns a `double`, so `Math.pow(2, 3)` is `8.0`, not `8`.
- The idiom `x % 2 == 0` tests for even; `x % 2 != 0` (or `== 1` for positive x) tests for odd. Expect this pattern in tracing questions and in FRQ logic.
- To trace a loop, make a small table with a column per variable and one row per pass. Writing the value after each iteration prevents off-by-one errors on the final count.
- When the inner bound is the outer variable (`j <= i`), do not multiply — add the per-row counts. A triangular pattern like 1 + 2 + 3 is the tell.
- For swap questions, resist the urge to assume a = b overwrites both. Trace all three statements: the temporary variable is what makes the exchange work correctly.
- Track an object’s state across a sequence of calls by keeping a running note of each instance variable. Mutator calls change it; accessor calls only read it.
- Remember the split: **instance** variables default (int → 0, boolean → false, object → null), but **local** variables must be initialized before use or the code will not compile.
- On the exam, directly reading or writing a `private` field from outside its class is always an error. Legal access outside the class must go through a `public` method.
- A subclass inherits public methods but not private fields directly — it reaches them through inherited methods or by passing values up with `super(...)`. `super(...)` must be the first line of the subclass constructor.
- An index runs from 0 to `length - 1`. To loop over every element, use `for (int i = 0; i < arr.length; i++)` — note the strict `<`, which stops correctly at the last valid index.
- When removing elements in a loop, remember each `remove(i)` shifts later elements left. Iterating forward with a normal index can skip elements — a very common FRQ trap.
- To traverse a full grid, use `for (int r = 0; r < m.length; r++)` outside and `for (int c = 0; c < m[0].length; c++)` inside. The outer loop walks rows, the inner walks columns.
- Seed a max/min search with `a[0]` and start the loop at index 1. Seeding with 0 can be wrong for arrays of all-negative numbers, and forgetting to update `max` leaves it stuck at the first value.
How to get a 5
- When removing elements from an ArrayList inside a standard for loop, iterate backward (from size()-1 down to 0) to avoid skipping elements as indices shift.
- On the free response, write clear, simple logic. You do not get extra points for "clever" or highly optimized code, but you do lose points for logic errors.
- Pay close attention to boundary conditions in arrays. The valid indices are 0 to arr.length - 1. A loop condition like i <= arr.length will cause an Exception.
- Remember that Strings are immutable. Methods like substring() or toUpperCase() return a *new* String; they do not change the original.
Key terms
Primitive vs. Reference Types — Primitives (int, double, boolean) store values directly. References (String, Objects, arrays) store memory addresses pointing to objects.
String Equality — Never use == to compare String contents; == checks if they are the exact same object in memory. Always use .equals().
Array vs. ArrayList Length — Array: arr.length (no parentheses). ArrayList: list.size() (with parentheses). String: str.length().
Short-Circuit Evaluation — In (A && B), if A is false, B is not evaluated. In (A || B), if A is true, B is not evaluated. Useful for avoiding NullPointerExceptions.
Overloading vs. Overriding — Overloading: Methods in same class with same name but different parameters. Overriding: Subclass redefines a method from superclass with identical signature.
Constructors and 'super' — Subclass constructors must call superclass constructor. If not done explicitly with super(), Java inserts super() (no-args) implicitly.
Polymorphism — A variable of superclass type can hold a subclass object. At runtime, the subclass's overridden method is executed (dynamic binding).
Math.random() — Returns a double in the range [0.0, 1.0). To get an int from min to max: (int)(Math.random() * (max - min + 1)) + min.
De Morgan's Laws — !(A && B) is equivalent to !A || !B. !(A || B) is equivalent to !A && !B.
Integer Division — In Java, dividing two ints truncates toward zero (e.g., 5 / 2 = 2). To get a decimal, cast one to double: (double) 5 / 2 = 2.5.
Enhanced for loop (for-each) — Syntax: for (Type item : collection). Cannot be used to modify the collection (no replacing elements, no removing).
2D Array Row/Col length — Rows: matrix.length. Columns: matrix[0].length (assuming a rectangular array).