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.
- **None of this is on the current exam.** The 2025 redesign of AP Computer Science A removed inheritance, polymorphism, `extends`, `super` and interfaces from the course. If you are revising for the exam, skip this lesson — Unit 3 is now tested on writing classes, instance variables, `this`, encapsulation, and static members and scope. This is here because inheritance is real Java that you will meet the moment you write code outside this course, and it costs you nothing to read once the exam is over.
- 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.
- Budget your time by section: the multiple-choice half is 40 questions in 90 minutes, so a code-trace item you cannot resolve in about two minutes should be marked and revisited, and the free-response half gives you roughly 22 minutes per question — enough to trace your own method on paper before you move on.
- Trace with a table, not in your head. Write one column per variable and one row per loop iteration; most missed multiple-choice points are off-by-one loop bounds or a variable updated in the wrong order, and both become obvious on paper.
- Check every division for the integer-division trap. If both operands are int, the result truncates. When a method returns a double, force double arithmetic by using a literal such as 100.0 or an explicit (double) cast, and say so in your answer.
- Honor the interface the problem hands you. Copy the method signatures exactly — the stated return type, parameter order, and access modifier — respect the given preconditions, and call any helper the prompt supplies or asks you to write, since calling it is usually worth a rubric point while re-implementing its logic risks that point and adds new bugs. Restate the postcondition in your own words before writing a line, because code that solves a different problem than the one specified earns nothing.
- You are not penalized for extra correct code, so never leave a part blank. Partial credit is awarded per rubric line, so an attempt that declares the variables, sets up the traversal, and returns something plausible often scores 2 or 3 of 4 points.
- Write the loop header and the return statement before the body, then handle the boundary cases graders always test: an empty array or list, a single element, the first and last index, and a search value that is not found. This guarantees a bound tied to length or size() and a correct return type on every path.
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 — && stops if the left side is false; || stops if the left side is true. This is why `if (s != null && s.length() > 0)` is safe and the reverse order is not.
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 (!a || !b); !(a || b) is (!a && !b). The operator flips along with each term, and forgetting the flip is a standard trap.
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).
What does 7 / 2 evaluate to in Java, and what does 7.0 / 2 evaluate to? — 7 / 2 is 3 — integer division truncates toward zero. 7.0 / 2 is 3.5, because one operand being a double promotes the whole expression to double arithmetic.
What is the value of −7 % 3 in Java? — −1. In Java the result of % takes the sign of the left operand, so −7 % 3 is −1, not 2.
Why must Strings be compared with equals instead of ==? — == compares references (whether two variables point to the same object), while equals compares the characters. Two Strings with identical contents can be different objects, so == may be false when equals is true.
What does s.substring(a, b) return? — The characters from index a up to but not including index b, so its length is b − a. s.substring(a) returns everything from index a to the end.
What does s.indexOf("x") return when "x" is not present? — −1. Any code that searches a String must test for −1 before using the result as an index.
What does it mean that Strings are immutable? — No String method changes the object it is called on. Methods such as substring, toUpperCase, replace, and concat all return new Strings, so their return values must be assigned or they are lost.
How does && short-circuit, and why does it matter? — If the left operand of && is false, the right operand is never evaluated (similarly, || stops when the left is true). This lets you guard a risky test, as in if (i < arr.length && arr[i] > 0).
State De Morgan’s laws for Java boolean expressions. — !(a && b) is equivalent to !a || !b, and !(a || b) is equivalent to !a && !b. Negating a compound condition flips both operands and swaps the operator.
What is the difference between passing a primitive and passing an object reference to a method? — Both are passed by value, but for an object the value copied is the reference. Reassigning the parameter never affects the caller; calling a mutator on the referenced object (or writing to an array element) does.
What is the purpose of the keyword this? — this refers to the current object. It disambiguates a field from a parameter of the same name (this.percent = percent) and lets one constructor or method call another on the same object.
When is a superclass constructor called, and what is the rule about super()? — Always first, before the subclass constructor body. An explicit super(args) call must be the first statement in the subclass constructor; if you omit it, Java inserts a call to the no-argument super().
What is the difference between overriding and overloading? — Overriding replaces an inherited method with the same signature in a subclass and is resolved at run time by the object’s actual type. Overloading defines several methods with the same name but different parameter lists in the same class and is resolved at compile time.