AP Computer Science A: Java Primitives, Control Flow, Classes, Objects, Strings, 1D/2D Arrays & ArrayLists
High-yield AP Computer Science A Units 1–8 review covering Java primitive types, integer division, casting, Math.random(), De Morgan's Laws, short-circuit evaluation, OOP classes, String methods, 1D/2D arrays, ArrayLists, and traversal traps.
- Level
- advanced
- Languages
- en → en
- Cards
- 32
- Markdown
- AP Computer Science A: Java Primitives, Control Flow, Classes, Objects, Strings, 1D/2D Arrays & ArrayLists (.md)
Flashcards (32)
| # | Front (Term / Question) | Back (Definition / Answer) | Example | Multiple-Choice Options |
|---|---|---|---|---|
| 1 | What are the three Java Primitive Data Types tested on the AP Computer Science A exam, and how do Integer Division (`/`) and the Modulus Operator (`%`) work? | • **Three AP Java Primitives**: `int` (32-bit signed integers from `Integer.MIN_VALUE` $= -2^{31}$ to `Integer.MAX_VALUE` $= 2^{31} - 1$), `double` (64-bit floating-point numbers), and `boolean` (`true` or `false`). *(Note: `String` is a reference/object type, NOT a primitive!)* • **Integer Division (`/`)**: When BOTH operands are `int`, Java **truncates toward zero** (drops the decimal fraction completely): `7 / 2` evaluates to `3`, `-7 / 2` evaluates to `-3`, and `3 / 5` evaluates to `0`. • **Modulus (`%`)**: Returns the remainder: `17 % 5` is `2`, `5 % 17` is `5`, `n % 2 == 0` checks if `n` is even, and `n % 10` extracts the rightmost digit of a positive integer `n` (while `n /= 10` removes the rightmost digit!). | ||
| 2 | List all 6 `ArrayList<E>` methods on the AP Computer Science A Java Quick Reference, including their exact return values and parameter orders. | 1. `int size()`: Returns the number of elements currently in the list. 2. `boolean add(E obj)`: Appends `obj` to the end of the list and **always returns `true`**. 3. `void add(int index, E obj)`: Inserts `obj` at `index` ($0 \le \text{index} \le \text{size()}$), shifting elements at `index` and higher to the right by 1. 4. `E get(int index)`: Returns the element at `index`. 5. `E set(int index, E obj)`: Replaces the element at `index` with `obj` and **returns the OLD element that was replaced**! 6. `E remove(int index)`: Removes the element at `index`, shifts subsequent elements **left by 1** (decrementing `size()`), and **returns the REMOVED element**! | ||
| 3 | On the AP CS A exam, what happens when you call `list.remove(2)` on an `ArrayList<Integer> list` containing `[10, 20, 2, 40]` vs. `list.remove(new Integer(2))`? | Because `ArrayList` has two overloaded `remove` methods—`E remove(int index)` and `boolean remove(Object obj)`: • **`list.remove(2)`**: Passes a primitive `int`, so it calls **`remove(int index)`**, removing the element at **index `2`** (returning `2` and leaving `[10, 20, 40]`). • **`list.remove(Integer.valueOf(2))` (or `new Integer(2)`)**: Passes an `Object`, removing the first occurrence of the value `2`. | ||
| 4 | What are the `Integer` and `Double` Wrapper Classes, what are Autoboxing and Unboxing, and why are they required for `ArrayList`? | Java `ArrayList<E>` can ONLY store **Object references**, NEVER primitive types (`ArrayList<int>` does not compile! You must write `ArrayList<Integer>` or `ArrayList<Double>` or `ArrayList<Boolean>`). • **Autoboxing**: Java automatically wraps a primitive `int` into an `Integer` object when added to an `ArrayList<Integer>` (`list.add(5);`). • **Unboxing**: Java automatically extracts the primitive `int` from an `Integer` object when assigned to an `int` or used in arithmetic (`int x = list.get(0) + 10;`). • **Constants**: `Integer.MIN_VALUE` ($-2^{31}$) and `Integer.MAX_VALUE` ($2^{31}-1$). | ||
| 5 | How do you use `Math.random()` to generate a random integer in the inclusive range `[min, max]`, and what do the AP Quick Reference `Math` methods return? | • `Math.random()` returns a `double` in the half-open interval **`[0.0, 1.0)`** ($0.0 \le r < 1.0$, never reaching $1.0$). • **Random `int` from `min` to `max` inclusive**: ```java int num = (int)(Math.random() * (max - min + 1)) + min; ``` (Here `max - min + 1` is the **number of possible integers**, and `min` is the **starting value**). • **Other AP `Math` Methods**: - `Math.abs(int x)` returns `int`; `Math.abs(double x)` returns `double`. - `Math.pow(double base, double exp)` ALWAYS returns a **`double`**. - `Math.sqrt(double x)` ALWAYS returns a **`double`**. | ||
| 6 | What happens when the `+` operator combines Strings and numbers in Java, such as `"Score: " + 3 + 4` vs. `3 + 4 + " points"`? | The `+` operator is evaluated from **left to right** unless overridden by parentheses. If EITHER operand is a `String`, `+` performs **String concatenation**: • `"Score: " + 3 + 4` $\rightarrow$ `"Score: 3" + 4` $\rightarrow$ **`"Score: 34"`**. • `"Score: " + (3 + 4)` $\rightarrow$ **`"Score: 7"`**. • `3 + 4 + " points"` $\rightarrow$ `7 + " points"` $\rightarrow$ **`"7 points"`**. | ||
| 7 | In Java Object-Oriented Programming (Unit 5), explain Encapsulation (`private` vs. `public`), Constructors, Accessor (Getter) vs. Mutator (Setter) methods, and the `this` keyword. | • **Encapsulation**: All **instance variables (fields) MUST be declared `private`** to protect internal object state; constructors and methods are typically `public`. • **Constructor**: Has the **exact same name as the class** and **NO return type (not even `void`!)**. Initializes all instance variables. If you write a method with `void ClassName()`, it is a regular method, NOT a constructor! • **Accessor (Getter)**: Returns the value of a private field without modifying the object. • **Mutator (Setter)**: Modifies one or more private instance variables (often `void`). • **`this` Keyword**: Refers to the current implicit object; used to resolve **variable shadowing** when a parameter has the same name as an instance variable (`this.name = name;`). | ||
| 8 | List all 7 `String` methods on the AP Computer Science A Java Quick Reference and explain their exact return types and edge cases. | Strings are **immutable** (0-indexed from `0` to `length() - 1`): 1. `int length()`: Returns number of characters. 2. `String substring(int from, int to)`: Returns characters from index `from` (inclusive) to `to` (**exclusive**, length $= \text{to} - \text{from}$). Note: `s.substring(i, i + 1)` gets the single-character String at index `i`; `s.substring(s.length())` returns `""` without error! 3. `String substring(int from)`: Returns from index `from` to the end of the String. 4. `int indexOf(String str)`: Returns the index of the **first** occurrence of `str`, or **`-1`** if not found. 5. `boolean equals(String other)`: Returns `true` if character sequences match. 6. `int compareTo(String other)`: Returns `< 0` if `this` comes lexicographically (ASCII order: `'0'–'9' < 'A'–'Z' < 'a'–'z'`) before `other`, `0` if equal, and `> 0` if `this` comes after `other`. | ||
| 9 | What is the 'Dangling `else`' problem in nested `if` statements without curly braces `{}` in Java? | Java ignores indentation! In nested `if` statements without braces, an **`else` clause ALWAYS pairs with the nearest preceding unmatched `if`**: ```java if (x > 0) if (y > 0) System.out.print("A"); else System.out.print("B"); ``` If `x = -5` and `y = 10`, **nothing is printed** because the `else` belongs to `if (y > 0)`, which is never reached when `x > 0` is `false`! | ||
| 10 | What does `System.out.println(obj)` print when passed an Object reference `obj`, and how does overriding `public String toString()` change that behavior? | Whenever an object reference is passed to `System.out.print` / `println` or concatenated with a `String` (`"Info: " + obj`), Java automatically invokes **`obj.toString()`**. If the class does not override `toString()`, it inherits `Object.toString()`, which prints `ClassName@HexHashCode`. Overriding `public String toString()` lets the class return a custom formatted `String` describing the object's fields. | ||
| 11 | How does Java pass Primitive arguments vs. Object Reference arguments into methods ('Pass-by-Value')? | Java is **strictly Pass-by-Value** for all parameters: 1. **Primitive Parameter (`int`, `double`, `boolean`)**: A copy of the value is passed. Modifying the parameter inside the method (`x = 99;`) has **ZERO effect** on the caller's original variable. 2. **Object Reference Parameter (`int[]`, `ArrayList`, custom Object, `String`)**: A copy of the **memory address (reference)** is passed: - **Reassigning the parameter reference** (`arr = new int[5];`) only changes the local parameter and does **NOT** affect the caller's array. - **Mutating the object through the reference** (`arr[0] = 99;` or `list.add(x);` or `obj.setScore(10);`) **DOES permanently modify** the caller's original object in heap memory! (Except `String` and `Integer`/`Double`, which are **immutable**). | ||
| 12 | When can and CANNOT you use an Enhanced `for` Loop (`for-each` loop: `for (Type x : collection)`) on a 1D Array or `ArrayList`? | In `for (int val : arr)`, the loop variable `val` is a **local copy** of each element: • **USE `for-each` when**: Reading elements to compute a sum, average, max/min, count matches, or calling mutator methods on object elements (`for (Student s : roster) s.addBonus(5);`). • **NEVER USE `for-each` when**: 1. You want to **modify/replace elements in the array or `ArrayList`** (`val = 0;` only changes the local variable `val`, leaving the array completely unchanged!). 2. You need the **index `i`** (e.g., comparing adjacent elements `arr[i]` and `arr[i + 1]`, or traversing backward). 3. You want to **add or remove elements** from an `ArrayList` during traversal (throws `ConcurrentModificationException`). | ||
| 13 | How does Type Casting (`(int)` and `(double)`) work in Java, including Operator Precedence and Rounding to the Nearest Integer? | • **Widening Conversion (`int` to `double`)**: Happens automatically (implicitly), e.g., `double x = 5;` sets `x` to `5.0`. • **Narrowing Conversion (`double` to `int`)**: Requires an explicit cast `(int)`, which **truncates toward zero**. • **High Precedence Trap**: The cast operator `(int)` or `(double)` has **HIGHER precedence than `*`, `/`, `+`, `-`**! Thus: - `(double) 5 / 2` casts `5` to `5.0` FIRST, then computes `5.0 / 2` $= \mathbf{2.5}$. - `(double) (5 / 2)` performs integer division `5 / 2` $= 2$ FIRST, then casts to $\mathbf{2.0}$! • **Rounding a `double d` to the Nearest `int`**: - Positive `d`: `(int)(d + 0.5)` - Negative `d`: `(int)(d - 0.5)`. | ||
| 14 | Why should you avoid testing two `double` values for exact equality with `a == b` after floating-point arithmetic, and how should you compare them instead? | Because binary floating-point representation cannot represent many base-10 decimals (such as `0.1`) exactly, `0.1 + 0.2` evaluates to `0.30000000000000004`, making `(0.1 + 0.2) == 0.3` evaluate to **`false`**! Instead, test whether their absolute difference is within a tiny tolerance ($\epsilon$): ```java if (Math.abs(a - b) < 0.0001) ``` | ||
| 15 | Write the standard AP CS A `String` loop algorithm to count or remove all occurrences of a target substring `sub` inside a String `str` using `indexOf` and `substring`. | • **Removing all occurrences of `sub` from `str`**: ```java int idx = str.indexOf(sub); while (idx != -1) { str = str.substring(0, idx) + str.substring(idx + sub.length()); idx = str.indexOf(sub); } ``` • **Counting character-by-character with `substring(i, i + 1)`**: ```java int count = 0; for (int i = 0; i <= str.length() - sub.length(); i++) { if (str.substring(i, i + sub.length()).equals(sub)) { count++; } } ``` | ||
| 16 | Write the standard algorithms for (a) Shifting a 1D Array Left by 1 position, (b) Shifting Right by 1 position (without overwriting all elements!), and (c) Reversing an Array in place. | • **(a) Shift Left by 1 (loop FORWARD from `0` to `length - 2`)**: ```java int first = arr[0]; for (int i = 0; i < arr.length - 1; i++) { arr[i] = arr[i + 1]; } arr[arr.length - 1] = first; ``` • **(b) Shift Right by 1 (MUST loop BACKWARD from `length - 1` down to `1`!)**: *(If you loop forward `arr[i + 1] = arr[i]`, you overwrite every element with `arr[0]`!)* ```java int last = arr[arr.length - 1]; for (int i = arr.length - 1; i > 0; i--) { arr[i] = arr[i - 1]; } arr[0] = last; ``` • **(c) Reverse in Place (loop only to `arr.length / 2`)**: ```java for (int i = 0; i < arr.length / 2; i++) { int temp = arr[i]; arr[i] = arr[arr.length - 1 - i]; arr[arr.length - 1 - i] = temp; } ``` | ||
| 17 | What is the classic `ArrayList` Removal Trap when removing matching elements in a forward `for` loop, and what are the two ways to fix it? | • **The Bug**: When `list.remove(i)` executes inside a forward loop (`for (int i = 0; i < list.size(); i++)`), the element that was at `i + 1` shifts left into index `i`, and then `i++` increments `i`—**skipping the adjacent element at index `i + 1` whenever two targets appear back-to-back**! • **Fix 1 (Decrement `i--` upon removal)**: ```java for (int i = 0; i < list.size(); i++) { if (list.get(i).equals(target)) { list.remove(i); i--; // re-check the new element at index i } } ``` • **Fix 2 (Traverse BACKWARD from `list.size() - 1` down to `0`)**: ```java for (int i = list.size() - 1; i >= 0; i--) { if (list.get(i).equals(target)) { list.remove(i); } } ``` | ||
| 18 | In an AP CS A Free-Response Question (FRQ 2: Class Design), what five checklist items guarantee 9/9 points when writing a complete Java class from a specification? | 1. **Class Header**: `public class ClassName`. 2. **Private Instance Variables**: Declare every required state variable as `private`. 3. **Constructor**: `public ClassName(params)` with **NO return type**, initializing all instance variables. 4. **Method Signatures**: Copy the exact `public`, return type, method name, and parameter types from the prompt. 5. **No Extraneous Output or Mutation**: Return the exact calculated value without `System.out.println` (unless asked) and without violating preconditions. | ||
| 19 | What is Method Overloading in Java, and can two overloaded methods differ ONLY by their return type? | **Method Overloading** occurs when two or more methods (or constructors) in the same class have the **exact same name** but **different parameter lists** (differing in the number, types, or order of parameters, e.g., `add(int x)` vs. `add(int i, int x)` vs. `add(double x)`). Overloaded methods **CANNOT differ only by return type or parameter variable names** (doing so causes a compile-time error). | ||
| 20 | When finding the Minimum or Maximum value in a 1D or 2D Array, what subtle bug occurs if you initialize `int max = 0;`? | If all numbers in the array are **negative** (e.g., `{-12, -5, -20}`), initializing `int max = 0;` will falsely return `0` (which isn't even in the array!) instead of `-5`. **Always initialize `max` and `min` to the first element of the array (`int max = arr[0];` or `mat[0][0]`)** or to `Integer.MIN_VALUE` / `Integer.MAX_VALUE`. | ||
| 21 | What happens if an `int` variable exceeds `Integer.MAX_VALUE` ($2,147,483,647$) or goes below `Integer.MIN_VALUE` ($-2,147,483,648$) in Java? | **Integer Overflow / Underflow**: Java does **NOT** throw an exception on integer overflow! Instead, the 32-bit two's-complement bits wrap around silently: • `Integer.MAX_VALUE + 1` wraps around to **`Integer.MIN_VALUE`** ($-2,147,483,648$). • `Integer.MIN_VALUE - 1` wraps around to **`Integer.MAX_VALUE`** ($+2,147,483,647$). | ||
| 22 | How is a 2D Array (`int[][] grid`) stored in Java as an 'array of arrays,' and how do you get the number of rows and the number of columns? | A 2D array `int[][] grid = new int[R][C];` is a 1D array of row references, where each `grid[r]` is a 1D `int[]` array of length `C`: • **Number of Rows**: **`grid.length`** • **Number of Columns**: **`grid[0].length`** (or `grid[r].length` for row `r`). • **Element at row `r`, column `c`**: `grid[r][c]` (row index ALWAYS comes first, column index second!). | ||
| 23 | Why must you NEVER use `==` to compare two `String` objects (or any Objects) for value equality in Java, and how does `==` differ from `.equals()`? | • **`==` on Object References**: Compares **memory addresses (references)**—returning `true` ONLY if both variables point to the **exact same object instance in memory** (**aliases**). While Java's string literal pool may sometimes make `"hi" == "hi"` evaluate to `true`, `new String("hi") == "hi"` is **`false`**! • **`.equals(Object other)`**: Compares the **actual character contents / state** of the two objects (`s1.equals(s2)` returns `true` if `s1` and `s2` contain the exact same sequence of characters). Always use `.equals()` for Strings and Wrapper objects! | ||
| 24 | What is the difference between a Shallow Copy (Alias) and a Deep Copy of an Array in Java? | • **Alias (`int[] b = a;`)**: Does NOT create a new array! Both `a` and `b` store the exact same memory address, so `b[0] = 99;` also changes `a[0]` to `99`. • **Deep Copy**: Allocates a brand-new array with `new int[a.length]` and copies each element in a loop: ```java int[] b = new int[a.length]; for (int i = 0; i < a.length; i++) { b[i] = a[i]; } ``` | ||
| 25 | Write the nested loops to traverse a 2D Array `int[][] mat` in (a) Row-Major Order, (b) Column-Major Order, and (c) Enhanced `for-each` Order. | • **(a) Row-Major Order (outer loop = rows, inner loop = columns)**: ```java for (int r = 0; r < mat.length; r++) { for (int c = 0; c < mat[0].length; c++) { System.out.print(mat[r][c] + " "); } } ``` • **(b) Column-Major Order (outer loop = columns, inner loop = rows)**: ```java for (int c = 0; c < mat[0].length; c++) { for (int r = 0; r < mat.length; r++) { System.out.print(mat[r][c] + " "); // still mat[r][c]! } } ``` • **(c) Enhanced `for-each` Traversal (Outer variable is a 1D array `int[] row`!)**: ```java for (int[] row : mat) { for (int val : row) { System.out.print(val + " "); } } ``` | ||
| 26 | What is Short-Circuit Evaluation in Java (`&&` and `||`), and how does it prevent `ArithmeticException` (division by zero), `NullPointerException`, and `IndexOutOfBoundsException`? | Java evaluates boolean expressions from **left to right** and stops as soon as the truth value is determined: • **`A && B`**: If `A` is **`false`**, Java does **NOT evaluate `B`** because `false && anything` is guaranteed to be `false`. • **`A || B`**: If `A` is **`true`**, Java does **NOT evaluate `B`** because `true || anything` is guaranteed to be `true`. • **Safe Guard Idioms** (guard MUST come FIRST on the left!): - `if (count != 0 && sum / count > 80)` (prevents division by zero) - `if (str != null && str.length() > 0)` (prevents `NullPointerException`) - `if (i >= 0 && i < arr.length && arr[i] == target)` (prevents `ArrayIndexOutOfBoundsException`). | ||
| 27 | How do you trace a `while` loop that extracts and sums all base-10 digits of a positive integer `int n`? | ```java int sum = 0; while (n > 0) { int digit = n % 10; // gets the ones digit sum += digit; n /= 10; // strips off the ones digit } ``` For `n = 472`: Iteration 1 (`digit = 2, sum = 2, n = 47`) $\rightarrow$ Iteration 2 (`digit = 7, sum = 9, n = 4`) $\rightarrow$ Iteration 3 (`digit = 4, sum = 13, n = 0`) $\rightarrow$ loop terminates with `sum = 13` (runs $d$ times where $d$ is the number of digits in `n`). | ||
| 28 | When comparing adjacent elements in a 1D array (`arr[i]` and `arr[i + 1]`) to check if an array is sorted in ascending order, what are the two classic mistakes to avoid on FRQs? | 1. **Loop Bound Trap**: The loop MUST stop at **`i < arr.length - 1`** (not `i < arr.length`, which throws `ArrayIndexOutOfBoundsException` when checking `arr[i + 1]` on the last element!). 2. **Premature `return true` Trap**: Never put `else return true;` inside the `for` loop (which only checks the very first pair `arr[0]` and `arr[1]`!). Instead, check for a violation (`if (arr[i] > arr[i + 1]) return false;`) inside the loop, and put **`return true;` AFTER the entire loop finishes**! | ||
| 29 | In a square $N \times N$ 2D Array `int[][] mat`, how do you access elements on the Main Diagonal vs. the Minor (Anti-) Diagonal? | With a single loop `for (int i = 0; i < mat.length; i++)`: • **Main Diagonal (top-left to bottom-right)**: Row index equals column index $\implies$ **`mat[i][i]`**. • **Anti-Diagonal (top-right to bottom-left)**: Row is `i` and column is `N - 1 - i` $\implies$ **`mat[i][mat.length - 1 - i]`**. | ||
| 30 | State De Morgan's Laws and Relational Operator Negations in Java Boolean Expressions. | • **De Morgan's Laws** (distribute `!` and flip `&&` $\leftrightarrow$ `||`): - `!(A && B)` is equivalent to **`!A || !B`** - `!(A || B)` is equivalent to **`!A && !B`** • **Negating Relational Operators** (watch the `=` boundary!): - `!(x > 5)` $\Longleftrightarrow$ **`x <= 5`** - `!(x >= 5)` $\Longleftrightarrow$ **`x < 5`** - `!(x == 5)` $\Longleftrightarrow$ **`x != 5`** *(Example: `!(x > 0 && y <= 10)` simplifies to `x <= 0 || y > 10`.)* | ||
| 31 | Distinguish between Instance Variables/Methods and `static` (Class) Variables/Methods in Java. | • **Instance Variables & Methods (Non-`static`)**: Every object created with `new` gets its own separate copy of instance variables; instance methods can access both instance variables and `static` variables. • **`static` Variables & Methods**: Belong to the **Class itself**, shared as a **single copy across all instances** (e.g., `private static int totalAccounts = 0;`). • **Crucial Compile-Time Rule**: A `static` method has **NO `this` reference** and therefore **CANNOT directly access non-`static` instance variables or call non-`static` instance methods** (causing a compile-time error!). | ||
| 32 | How do you declare, instantiate, and access a 1D Array in Java, what are the default values of uninitialized elements, and how does `.length` work? | • **Declaration & Instantiation**: ```java int[] nums = new int[5]; int[] primes = {2, 3, 5, 7, 11}; ``` • **Default Element Values** when created with `new type[n]`: - `int[]` $\rightarrow$ `0` - `double[]` $\rightarrow$ `0.0` - `boolean[]` $\rightarrow$ `false` - `String[]` or any Object array $\rightarrow$ **`null`** (calling a method on an uninitialized element throws `NullPointerException`!). • **Length**: `arr.length` is a **public final field (NO parentheses!)**, unlike `str.length()` (method) and `list.size()` (method). Valid indices are `0` to `arr.length - 1`. |