CS A

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

How to get a 5

Key terms

Primitive vs. Reference TypesPrimitives (int, double, boolean) store values directly. References (String, Objects, arrays) store memory addresses pointing to objects.
String EqualityNever use == to compare String contents; == checks if they are the exact same object in memory. Always use .equals().
Array vs. ArrayList LengthArray: 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. OverridingOverloading: 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.
PolymorphismA 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 DivisionIn 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 lengthRows: 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.