AP CSA Reference Sheet 2026 - Complete Java Quick Reference Guide
AP CSA Java Reference Sheet 2026
Every method, operator, syntax pattern, and exam trap on one page. Official College Board quick reference — expanded with examples, gotchas, and FRQ tips.
Jump to Section
Primitive Data Types Unit 1
Java has three primitive types tested on the AP CSA exam. Primitives store values directly (unlike objects, which store references).
| Type | Size | Range / Values | Default | Example |
|---|---|---|---|---|
int |
32-bit | −2,147,483,648 to 2,147,483,647 | 0 | int score = 95; |
double |
64-bit | ~±1.8 × 10308, 15-16 sig digits | 0.0 | double gpa = 3.85; |
boolean |
1-bit |
true or false only |
false | boolean passed = true; |
5 / 2 = 2 (NOT 2.5). Both operands are int, so the result is int and truncates. To get 2.5, cast first: (double) 5 / 2 or use 5.0 / 2.
Casting Between Types
int a = 7; double b = (double) a / 2; // b = 3.5 (cast BEFORE division) int c = (int) 3.9; // c = 3 (truncates, does NOT round) int d = (int) (3.9 + 0.5); // c = 4 (manual round trick)
int → double is automatic (widening). double → int requires explicit cast (narrowing). Casting always truncates, never rounds.
Operators Units 1–2
Arithmetic Operators
| Op | Name | Example | Result | Watch Out |
|---|---|---|---|---|
+ |
Addition / concat | 3 + 4 |
7 |
With Strings, converts to concat |
- |
Subtraction | 10 - 3 |
7 |
|
* |
Multiplication | 4 * 5 |
20 |
|
/ |
Division | 7 / 2 |
3 |
Int/int = int (truncates!) |
% |
Modulo (remainder) | 7 % 3 |
1 |
Result sign matches dividend |
Compound Assignment Operators
| Shorthand | Equivalent | Example |
|---|---|---|
x += 5 |
x = x + 5 |
x += 3 |
x -= 5 |
x = x - 5 |
count -= 1 |
x *= 2 |
x = x * 2 |
total *= rate |
x /= 2 |
x = x / 2 |
n /= 10 |
x %=3 |
x = x % 3 |
n %= 2 |
x++ |
x = x + 1 |
i++ |
x-- |
x = x - 1 |
count-- |
Relational Operators Unit 2
| Op | Meaning | Returns |
|---|---|---|
== |
Equal to | boolean |
!= |
NOT equal to | boolean |
< |
Less than | boolean |
> |
Greater than | boolean |
<= |
Less than or equal | boolean |
>= |
Greater than or equal | boolean |
Logical Operators
| Op | Name | True when… | Short-circuits? |
|---|---|---|---|
&& |
AND | Both sides are true | Yes — stops at first false
|
|| |
OR | At least one side true | Yes — stops at first true
|
! |
NOT | Operand is false | N/A (unary) |
!(a && b) ≡ !a || !b | !(a || b) ≡ !a && !b
String Methods Unit 1
substring.
| Method Signature | Returns | Description |
|---|---|---|
int length() |
int |
Number of characters in the String |
String substring(int from, int to) |
String |
Chars from index from up to but NOT including to
|
String substring(int from) |
String |
Chars from from to end of String |
int indexOf(String str) |
int |
First index of str, or -1 if not found |
boolean equals(Object other) |
boolean |
True if same sequence of characters |
int compareTo(String other) |
int |
Negative if less, 0 if equal, positive if greater (lexicographic) |
Detailed Examples
String s = "HelloWorld"; s.length() // 10 s.substring(0, 5) // "Hello" (index 0,1,2,3,4 — stops BEFORE 5) s.substring(5) // "World" (from index 5 to end) s.indexOf("World") // 5 s.indexOf("xyz") // -1 (not found) s.equals("HelloWorld") // true s.compareTo("Hello") // positive ("HelloWorld" > "Hello") s.compareTo("Helloz") // negative ('W' < 'z' in Unicode) // charAt — NOT on quick ref but commonly tested: s.charAt(0) // 'H' (char, not String)
substring Formula
Length of extracted string = to − from
"Hello".substring(1,3) → "el" (3−1=2 chars)
== vs .equals()
== compares references (addresses)..equals() compares content.
Always use .equals() for Strings.
toUpperCase(), toLowerCase(), charAt(int index), trim(), equalsIgnoreCase(String other)
Math Class Unit 1
| Method Signature | Returns | Description |
|---|---|---|
static int abs(int x) |
int |
Absolute value of integer |
static double abs(double x) |
double |
Absolute value of double |
static double pow(double base, double exp) |
double |
base raised to the power exp |
static double sqrt(double x) |
double |
Square root of x |
static double random() |
double |
Random number in [0.0, 1.0) — includes 0, excludes 1 |
random() Patterns — High-Frequency MCQ Topic
// Random int from 0 to n-1 (n possibilities): (int)(Math.random() * n) // Random int from 1 to n (inclusive): (int)(Math.random() * n) + 1 // Random int from low to high (inclusive): (int)(Math.random() * (high - low + 1)) + low // Examples: (int)(Math.random() * 6) + 1 // 1 to 6 (simulates die roll) (int)(Math.random() * 100) // 0 to 99 (int)(Math.random() * 100) + 1 // 1 to 100
Other Math Examples
Math.abs(-7) // 7 Math.pow(2, 10) // 1024.0 (always returns double) Math.sqrt(16) // 4.0 (always returns double) (int) Math.pow(2,3) // 8 (cast to int when needed)
Math.pow(2, 3) returns 8.0 not 8. Cast to int if you need an integer result. Same for Math.sqrt.
Integer & Double Wrapper Classes Unit 1
Wrapper classes let primitives be used as objects (required for ArrayList). Java handles autoboxing and unboxing automatically.
| Constant / Method | Value / Returns | Description |
|---|---|---|
Integer.MIN_VALUE |
-2147483648 |
Smallest possible int. Useful as starting max in algorithms. |
Integer.MAX_VALUE |
2147483647 |
Largest possible int. Useful as starting min in algorithms. |
Double.MIN_VALUE |
~4.9 × 10-324 | Smallest positive double (NOT most negative) |
Double.MAX_VALUE |
~1.8 × 10308 | Largest positive double |
// Autoboxing: int -> Integer (automatic) ArrayList<Integer> nums = new ArrayList<>(); nums.add(42); // 42 autoboxed to Integer // Unboxing: Integer -> int (automatic) int x = nums.get(0); // Integer unboxed to int // Finding max using Integer.MIN_VALUE int max = Integer.MIN_VALUE; for (int val : nums) { if (val > max) max = val; }
Double.MAX_VALUE and negate: double min = Double.MAX_VALUE;
Scanner & File Reading Unit 1 — New 2025-2026
Scanner is a new addition to the AP CSA exam. The same Scanner methods work whether you are reading from a file or from the keyboard — only the constructor argument changes.
Scanner Method Reference
| Method | Returns | Reads / Behavior |
|---|---|---|
nextInt() |
int |
Next token, parsed as int. Throws exception if not an int. |
nextDouble() |
double |
Next token, parsed as double. |
next() |
String |
Next whitespace-delimited token (single word). Does NOT include newline. |
nextLine() |
String |
Entire next line including spaces. Consumes the newline character. |
hasNext() |
boolean |
True if any more tokens remain in the file. |
hasNextInt() |
boolean |
True if the next token can be parsed as an int. |
hasNextDouble() |
boolean |
True if the next token can be parsed as a double. |
close() |
void |
Releases the file resource. Always call when done. |
Pattern 1 — Read ints from file into an array
Use this when the file contains a known count of integers, or when you first read the count from line 1.
import java.util.Scanner; import java.io.File; // File contents: // 5 // 10 20 30 40 50 Scanner sc = new Scanner(new File("numbers.txt")); int count = sc.nextInt(); // read the count from line 1: 5 int[] data = new int[count]; // allocate array of that size for (int i = 0; i < data.length; i++) { data[i] = sc.nextInt(); // read each int directly into array } sc.close(); // data = {10, 20, 30, 40, 50}
Pattern 2 — Read ints from file into an ArrayList
Use this when you do not know how many values the file contains. hasNextInt() drives the loop.
import java.util.Scanner; import java.util.ArrayList; import java.io.File; // File contents: one int per line, unknown count // 42 // 17 // 99 // 5 Scanner sc = new Scanner(new File("scores.txt")); ArrayList<Integer> scores = new ArrayList<>(); while (sc.hasNextInt()) { scores.add(sc.nextInt()); // autoboxes int to Integer } sc.close(); // scores = [42, 17, 99, 5] -- size grew automatically
Pattern 3 — Read String tokens with next(), convert with parseInt()
next() always reads a String. Use Integer.parseInt() to convert a numeric string to an int. This is common when file data is mixed (names and numbers on same line).
import java.util.Scanner; import java.io.File; // File contents: name score per line // Alice 95 // Bob 87 // Carol 91 Scanner sc = new Scanner(new File("grades.txt")); ArrayList<Integer> gradeList = new ArrayList<>(); while (sc.hasNext()) { String name = sc.next(); // reads "Alice", "Bob", etc. String token = sc.next(); // reads "95", "87", etc. as String int grade = Integer.parseInt(token); // converts String "95" -> int 95 gradeList.add(grade); } sc.close(); // gradeList = [95, 87, 91]
Pattern 4 — Read full lines with nextLine()
Use nextLine() when each line should be kept as a single String, including spaces.
import java.util.Scanner; import java.io.File; // File contents: // Hello World // AP Computer Science A // Java is great Scanner sc = new Scanner(new File("lines.txt")); ArrayList<String> lines = new ArrayList<>(); while (sc.hasNext()) { lines.add(sc.nextLine()); // each full line as one String } sc.close(); // lines = ["Hello World", "AP Computer Science A", "Java is great"]
parseInt() — String to int conversion
| Method | Returns | Example | Result |
|---|---|---|---|
Integer.parseInt(String s) |
int |
Integer.parseInt("42") |
42 |
Double.parseDouble(String s) |
double |
Double.parseDouble("3.14") |
3.14 |
String.valueOf(int n) |
String |
String.valueOf(42) |
"42" |
"" + n |
String |
"" + 42 |
"42" (shorthand) |
next() vs nextLine()
next() — reads one token (stops at whitespace). "Hello World" takes two calls.
nextLine() — reads entire line including spaces. "Hello World" is one call.
Both advance past what they read.
nextInt() vs parseInt()
nextInt() — Scanner reads and converts directly. Use when file has bare numbers.
Integer.parseInt(sc.next()) — read as String first, then convert. Use when numbers are mixed with text or you need the raw String too.
nextInt() (or nextDouble()), the newline character \n remains in the buffer. The next call to nextLine() reads that empty leftover instead of the next real line. Fix: insert an extra sc.nextLine() call to consume the leftover newline before reading real lines.
Scanner sc = new Scanner(new File("data.txt")); int count = sc.nextInt(); // reads the int... sc.nextLine(); // ...consume leftover newline <-- FIX String line = sc.nextLine(); // now reads the actual next line correctly
hasNext(), hasNextInt(), or hasNextDouble() as your while-loop condition when reading a file. Never assume you know the exact number of lines. The loop exits cleanly when the file ends with no exception thrown.
Arrays (1D) Unit 4
Arrays store a fixed number of elements of the same type. Size cannot change after creation. Indexed 0 to length - 1.
Declaration & Initialization
// Declare and allocate (default values: 0, 0.0, false, null) int[] scores = new int[5]; // Declare with initializer list int[] primes = {2, 3, 5, 7, 11}; // Access and modify primes[0] = 2; // first element primes[primes.length-1] // last element (length-1, not length!)
Traversal Patterns
int[] arr = {10, 20, 30, 40, 50}; // Standard for loop (use when you need index) for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } // Enhanced for loop (read-only, clean) for (int val : arr) { System.out.println(val); } // Common algorithms int sum = 0; int max = arr[0]; // initialize to first element, not 0 for (int val : arr) { sum += val; if (val > max) max = val; }
| Array Property | Syntax | Notes |
|---|---|---|
| Length | arr.length |
No parentheses (not a method) |
| First element | arr[0] |
Always index 0 |
| Last element | arr[arr.length - 1] |
NOT arr[arr.length]
|
| Default int | 0 |
All ints start at 0 |
| Default double | 0.0 |
|
| Default boolean | false |
|
| Default object | null |
arr[arr.length] crashes at runtime. Valid indices are 0 through length−1 only. In for loops: i < arr.length (not i <= arr.length).
ArrayList Unit 4
| Method Signature | Returns | Description |
|---|---|---|
int size() |
int |
Number of elements in the list |
boolean add(E obj) |
boolean |
Appends obj to end; always returns true |
void add(int index, E obj) |
void |
Inserts obj at index; shifts right |
E get(int index) |
E |
Returns element at index (no removal) |
E set(int index, E obj) |
E |
Replaces element; returns OLD value |
E remove(int index) |
E |
Removes and returns element; shifts left |
Detailed Usage
import java.util.ArrayList; ArrayList<Integer> list = new ArrayList<>(); list.add(10); // [10] list.add(20); // [10, 20] list.add(30); // [10, 20, 30] list.add(1, 15); // [10, 15, 20, 30] (inserts at index 1) list.size() // 4 list.get(0) // 10 list.set(0, 99) // returns 10, list is now [99, 15, 20, 30] list.remove(1) // returns 15, list is now [99, 20, 30]
Traversal & Safe Removal
// Safe removal while traversing: iterate BACKWARD for (int i = list.size() - 1; i >= 0; i--) { if (list.get(i) < 0) { list.remove(i); // safe: only affects indices after i } } // Enhanced for loop (read-only — do NOT modify during this) for (Integer val : list) { System.out.println(val); }
array vs ArrayList
| Feature | array | ArrayList |
|---|---|---|
| Size | Fixed | Dynamic |
| Types | Primitives OK | Objects only |
| Length | .length |
.size() |
| Access | arr[i] |
list.get(i) |
set() vs add()
set(i, val) — replaces at index i. Size unchanged.
add(i, val) — inserts at index i. Size increases. Elements shift right.
2D Arrays Unit 4
A 2D array is an array of arrays. Think of it as a grid with rows and columns. Accessed as arr[row][col].
// Declaration and allocation (3 rows, 4 columns) int[][] grid = new int[3][4]; // Initializer list int[][] matrix = {{1,2,3}, {4,5,6}, {7,8,9}}; // Dimensions grid.length // number of rows (3) grid[0].length // number of columns (4) // Row-major traversal (outer=row, inner=col) — most common for (int r = 0; r < matrix.length; r++) { for (int c = 0; c < matrix[r].length; c++) { System.out.print(matrix[r][c] + " "); } System.out.println(); } // Enhanced for loop version for (int[] row : matrix) { for (int val : row) { System.out.print(val + " "); } }
arr[r][c]). Column-major: outer loop iterates columns (arr[r][c] but outer is c). FRQ questions sometimes specify which order to process. Row-major is far more common.
Control Flow Unit 2
if / else if / else
if (condition1) { // runs if c1 true } else if (condition2) { // runs if c1 false, c2 true } else { // runs if all false }
while loop
while (condition) { // update condition // inside loop } // check: will it terminate?
for loop
for (init; condition; update) { // body } // i=0; i
enhanced for (for-each)
for (Type var : collection) { // read-only traversal // cannot modify list here }
Loop Algorithm Patterns
| Pattern | Template | Use Case |
|---|---|---|
| Accumulator | sum += val |
Running total, product |
| Counter | if (cond) count++ |
Count occurrences |
| Find max | if (val > max) max = val |
Track largest seen |
| Find min | if (val < min) min = val |
Track smallest seen |
| Linear search | if (val == target) return i |
Find index of value |
| String build | result += s.substring(i,i+1) |
Rebuild/filter string |
Class Structure Template Unit 3
public class ClassName { // Instance variables (always private) private String name; private int value; // Constructor (same name as class, no return type) public ClassName(String name, int value) { this.name = name; // this.x = parameter x this.value = value; } // Accessor (getter) — returns value, no modification public String getName() { return name; } // Mutator (setter) — modifies value, returns void public void setValue(int newValue) { value = newValue; } // toString — override for readable output public String toString() { return "ClassName[" + name + ", " + value + "]"; } }
public — accessible anywhereprivate — accessible only within classMath.random() is static — no object needed.this.x = x
private. Methods that expose/change them = public. This is always the pattern on FRQs.void/return type). Constructors are called with new.Top Exam Traps & Common Errors
These are the highest-frequency error sources in both MCQ and FRQ. Know them cold.
Unit 1 Traps
-
Integer division truncates:
7 / 2 = 3, not 3.5. Cast first:(double) 7 / 2. -
String == vs .equals():
==checks reference equality..equals()checks content. Always use.equals()for Strings. -
substring end is exclusive:
"Hello".substring(1, 3)is"el", not"ell". - Math.random() range is [0.0, 1.0): Multiply and cast correctly for integer ranges.
- Math.pow / sqrt always return double: Cast to int when an integer result is needed.
-
String concatenation with +:
"val: " + 3 + 2gives"val: 32", not"val: 5". Use parentheses:"val: " + (3 + 2).
Unit 2 Traps
-
= vs == in conditions:
if (x = 5)is an assignment (compiler error in Java). Must use==. -
Off-by-one errors:
i <= arr.lengthcauses crash. Usei < arr.length. - Infinite loop: Loop condition never becomes false. Check that the update step actually progresses toward termination.
-
Short-circuit evaluation: In
a && b, ifais false,bis never evaluated. Can prevent null pointer errors. -
De Morgan’s Laws:
!(a && b)≠!a && !b. Must flip the operator:!a || !b.
Unit 3 Traps
-
Forgetting this keyword: When parameter name matches instance variable name, use
this.name = name. -
Local variable shadows instance variable: Declaring
int value = 5;inside a method creates a local, not updating the instance variable. -
Return type mismatch: A method declared
intthat returnsdouble, orvoidthat has a return with a value, causes compile error. -
Static method accessing instance data: Static methods cannot reference
thisor non-static instance variables.
Unit 4 Traps
-
array.length vs list.size(): Arrays use
.length(no parens). ArrayList uses.size()(with parens). -
ArrayList requires wrapper types:
ArrayListis invalid. Must useArrayList. -
Modifying ArrayList during for-each: Causes
ConcurrentModificationException. Use backward for loop for safe removal. -
2D array: row vs column dimension:
arr.lengthis row count.arr[0].lengthis column count. Do NOT usearr.lengthfor both. -
Initializing max to 0: If all values are negative, max stays 0 (wrong). Initialize to first element or
Integer.MIN_VALUE.
FRQ Section Quick Reference
| FRQ Type | What to Do | Key Methods/Syntax | Units |
|---|---|---|---|
| Methods & Control Structures | Write methods using conditionals and loops. Given class structure, fill in method bodies. |
for, while, if/else, String methods |
1–2 |
| Class Writing | Write complete class from scratch: constructor, instance vars, getters, setters, methods. |
private, this, constructor syntax |
3 |
| Array / ArrayList | Traverse and manipulate 1D collection. Often: filter, search, accumulate, or rebuild. |
get(), set(), add(), remove(), backward loop |
4 |
| 2D Array | Process matrix data with nested loops. Row-major or col-major traversal. |
arr[r][c], nested for, arr[r].length
|
4 |
FRQ Penalty Avoidance
- No
[]vs()confusion on collections - No
System.out.printlninside return methods - No out-of-bounds in array traversal
- Declare all local variables before use
- Don’t destroy parameter/instance data by accident
No-Penalty Shortcuts Allowed
- Missing semicolons (if intent is clear)
- Missing curly braces (if indent is clear)
- Missing
publicon class/constructor -
.lengthvs.size()confusion -
[i,j]instead of[i][j]
Ready to Put This to Use?
Daily practice questions, full FRQ solutions, and complete unit study guides — all free.
Frequently Asked Questions
(int)(Math.random() * n) + low where n is the number of possible values and low is the smallest. For example, a random integer from 1 to 6: (int)(Math.random() * 6) + 1. For 0 to 9: (int)(Math.random() * 10). The range of Math.random() is [0.0, 1.0) — includes 0, excludes 1.length field (no parentheses): arr.length. ArrayLists use the size() method (with parentheses): list.size(). This is a frequent MCQ trap. Additionally, arrays have a fixed size set at creation, while ArrayLists grow and shrink dynamically as you add and remove elements.Related AP CSA Resources
Get in Touch
Whether you're a student, parent, or teacher — I'd love to hear from you.
Just want free AP CS resources?
Enter your email below and check the subscribe box — no message needed. Students get daily practice questions and study tips. Teachers get curriculum resources and teaching strategies.
Message Sent!
Thanks for reaching out. I'll get back to you within 24 hours.
tanner@apcsexamprep.com
Courses
AP CSA, CSP, & Cybersecurity
Response Time
Within 24 hours
Prefer email? Reach me directly at tanner@apcsexamprep.com