
































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!

































AP CS A: AP Computer Science A Prep with Detailed Rationales Course Code: AP CS A Course Name: AP Computer Science A Topic: Java Object-Oriented Design & Array Traversals Code Snippets Academic Year: 2026/
📋 STUDY CORE TOPICS OUTLINE
In Java, when evaluating reference variable assignment, assigning one object reference to another creates aliasing. Consider the following snippet: Rectangle r1 = new Rectangle(5, 10); Rectangle r2 = r1; r2.setWidth(15); Which statement correctly describes the outcome regarding r1.getWidth()? A) r1.getWidth() returns 5 because r2 is an independent primitive copy of r1. B) r1.getWidth() returns 15 because r1 and r2 reference the exact same memory address. C) r1.getWidth() throws a NullPointerException because r2 severed the link to r1. D) r1.getWidth() returns 10 because width and height modifications are immutable by default. CORRECT ANSWER: B) r1.getWidth() returns 15 because r1 and r2 reference the exact same memory address. RATIONALE: In Java, non-primitive variables hold object references (memory pointers), not distinct copies of the object itself. The assignment statement r2 = r1 copies the reference stored in r1 into r2. Both variables now point to the identical Rectangle instance on the heap. Modifying the state of the object via r2.setWidth(15) updates the underlying object, so calling r1.getWidth() returns the newly mutated value
int a = 7; int b = 2; double result = a / b;What value is stored in result? A) 3.5 B) 3.0 C) 3 D) 4.0 CORRECT ANSWER: B) 3.0 RATIONALE: Both a and b are primitive int data types. In Java, integer division truncates any fractional remainders, so 7 / 2 evaluates to the integer 3. Next, the assignment operator performs an implicit widen casting of integer 3 to double, producing 3.0. To receive 3.5, at least one operand must be cast to double prior to division (e.g., (double) a / b). Option A fails to recognize truncation prior to assignment. Option C correctly identifies the math truncation but misses the variable target type double. Option D is an erroneous rounding attempt.
Consider the following implementation of a static method vs. instance variable access :
public class Counter { private int count = 0; public static void increment() { // Line 4 } } ## ``` What occurs if **`count++;`** is placed on Line 4? A) The variable `count` increments by 1 every time `Counter.increment()` is called. B) **A compile-time error occurs because a static method cannot directly access a non-static instance field.** C) The code compiles, but throws a `NullPointerException` at runtime. D) The variable `count` is converted into a static variable implicitly by the JVM. *CORRECT ANSWER:* B) A compile-time error occurs because a static method cannot directly access a non-static instance field. *RATIONALE:* Static methods belong to the class level and exist independently of any individual object instantiation. Because non-static instance variables like `count` belong to specific object instances on the heap, a static method lacks an implicit `this` reference and cannot access instance variables directly. Option A assumes instance fields can be referenced without an instance context. Option C is wrong because reference errors happen at compile time, not runtime. Option D is incorrect because Java does not alter field access scopes dynamically. --- #### Question 5 Consider the following loop traversing an array of integers demonstrating **1D array element modification** : ```java int[] nums = {4, 8, 12, 16, 20}; for (int i = 0; i < nums.length - 1; i++) { nums[i] = nums[i + 1] - nums[i]; }What are the elements of nums after the loop completes execution? A) {4, 4, 4, 4, 20} B) {4, 4, 4, 4, 20} C) {4, 4, 4, 4, 4}
Consider the following method designed to evaluate short-circuit evaluation in boolean logic:
public static boolean check(int[] arr, int index) { return index < arr.length && arr[index] != 0; }If arr = {1, 2, 3} and index = 3, what is the result of calling check(arr, index)? A) Throws an ArrayIndexOutOfBoundsException. B) Returns false without throwing an exception. C) Returns true. D) Throws a NullPointerException. CORRECT ANSWER: B) Returns false without throwing an exception. RATIONALE: Java uses short-circuit evaluation for the logical AND (&&) operator. The left operand index < arr.length (3 < 3) evaluates to false. Because both operands must be true for the AND expression to be true, Java immediately short- circuits and skips evaluating the right-hand operand (arr[index] != 0). Thus, no out-of- bounds access occurs at arr[3], and the method safely returns false. Option A would occur if the single non-short-circuiting & operator were used instead.
Consider the following Java method utilizing string immutability and concatenation :
public static void main(String[] args) { String str = "Java"; str.concat(" World"); System.out.println(str); } ## ``` What is printed to the console upon calling **`main`**? A) `Java World` B) **`Java`** C) `null` D) `JavaWorld` *CORRECT ANSWER:* B) `Java` *RATIONALE:* Strings in Java are immutable objects. Calling methods like `.concat()`, `.substring()`, or `.toUpperCase()` returns a brand new `String` object containing the modified characters; they never mutate the existing instance in memory. Because the return value of `str.concat(" World")` is ignored and not re-assigned back to `str`, `str` continues to reference the original `"Java"` literal. To print `"Java World"`, the line must be written as `str = str.concat(" World");`. --- #### Question 9 Consider the code snippet evaluating **wrapper class autoboxing and unboxing** : ```java Integer x = 100; Integer y = 100; Integer a = 200; Integer b = 200; System.out.println((x == y) + " " + (a == b));What is the exact output of this code snippet in standard Java? A) true true B) false false C) true false D) false true
Consider the following method designed to perform a linear search for minimum element index :
public static int findMinIndex(int[] arr) { int minIdx = 0; for (int i = 1; i < arr.length; i++) { if (arr[i] < arr[minIdx]) { minIdx = i; } } return minIdx; }If arr is {15, 8, 22, 8, 30}, what value is returned by findMinIndex(arr)? A) 1 B) 1 C) 3 D) 8 CORRECT ANSWER: B) 1 RATIONALE: The algorithm initializes minIdx = 0 (value 15).
Analyze the following code block involving parameter passing mechanics in Java :
public static void modify(int x, int[] arr) { x = 50; arr[0] = 99; } public static void main(String[] args) { int val = 10; int[] nums = {1, 2, 3}; modify(val, nums); System.out.println(val + " " + nums[0]); }What is printed when main is executed? A) 50 99 B) 10 99 C) 10 1 D) 50 1 CORRECT ANSWER: B) 10 99 RATIONALE: Java strictly uses pass-by-value. For primitive types (like val), a copy of the value (10) is passed into modify. Changes made to x inside the method do not affect val. However, for reference types (like nums), the value passed to the method is a copy of the reference pointer. Both nums in main and arr inside modify point to the exact same array in memory. Modifying arr[0] directly mutates the actual array on the heap, which is visible in main. Thus, val remains 10 and nums[0] becomes 99.
C) Column-major can only be used on square matrices, while row-major works on rectangular matrices. D) Row-major creates temporary array copies, whereas column-major operates directly on memory. CORRECT ANSWER: B) Row-major iterates using matrix[r][c], while column- major swaps loop indexing to iterate by outer columns and inner rows matrix[r][c]. RATIONALE: In Java 2D arrays, memory is stored as an array of arrays (row-major structure). Standard row-major traversal uses an outer loop for rows (r) and an inner loop for columns (c). Column-major traversal reverses the nesting: the outer loop runs over column indices (c) and the inner loop runs over row indices (r), evaluating matrix[r][c] column by column. Option A provides a conceptual description, but Option B correctly identifies the exact syntactic loop nesting swap used in AP CS A standard questions.
Consider the following subclass constructor scenario illustrating the super keyword requirements :
class Vehicle { private String brand; public Vehicle(String b) { brand = b; } } class Car extends Vehicle { private int doors; public Car(String b, int d) { // Line 7 doors = d; } }Which code segment must be placed on Line 7 to ensure compilation? A) Vehicle(b); B) super(b); C) this.brand = b; D) super.brand = b; CORRECT ANSWER: B) super(b); RATIONALE: Parent class Vehicle defines a custom constructor accepting a String and does not provide a default no-argument constructor. Therefore, subclass Car must explicitly invoke the parent constructor using super(b); as the absolute first statement inside its constructor. Option A is invalid syntax. Options C and D fail because brand is marked private in Vehicle and cannot be accessed directly by subclasses.
What occurs when a subclass defines a method with the exact same method signature (name and parameter list) as a method in its superclass, demonstrating method overriding? A) A compile-time error occurs due to duplicate method definitions. B) The subclass method overrides the superclass method, enabling dynamic binding at runtime. C) The subclass method overloads the superclass method. D) Both methods run sequentially whenever the subclass method is called. CORRECT ANSWER: B) The subclass method overrides the superclass method, enabling dynamic binding at runtime. RATIONALE: Method overriding occurs when a subclass re-defines an inherited method with the exact same name, return type, and parameter list. At runtime, Java uses dynamic binding to execute the overridden method version corresponding to the actual object type, not the reference type. Option C defines method overloading, which requires identical method names but differing parameter lists.
int[] numbers = {10, 20, 30, 40}; int sum = 0; for (int i = 0; i <= numbers.length; i++) { sum += numbers[i]; }
What happens when this code is compiled and executed? A) Computes `sum` as `100` smoothly. B) **Compiles successfully, but throws an `ArrayIndexOutOfBoundsException` at runtime.** C) Fails to compile due to a syntax error on the loop boundary. D) Initializes `sum` to `0` without running the loop body. *CORRECT ANSWER:* B) Compiles successfully, but throws an `ArrayIndexOutOfBoundsException` at runtime. *RATIONALE:* Valid array indices for an array of length 4 are `0, 1, 2, 3`. The loop condition `i <= numbers.length` allows `i` to reach `4`. When `i = 4`, evaluating `numbers[4]` attempts to access an index outside the allocated array boundaries, causing Java to throw an `ArrayIndexOutOfBoundsException` at runtime. To prevent this, the condition must use `< numbers.length`. --- #### Question 19 Analyze the following code fragment containing **nested loop execution count** : ```java int count = 0; for (int k = 0; k < 4; k++) { for (int j = 0; j < 3; j++) { count++; } } ## ``` What is the final value of **`count`**? A) `7` B) **`12`** C) `9` D) `16` *CORRECT ANSWER:* B) `12` *RATIONALE:* The outer loop runs 4 times (`k = 0, 1, 2, 3`). For each iteration of the outer loop, the inner loop runs 3 times (`j = 0, 1, 2`). The total number of executions of `count++` is given by the product of the loop iterations: `4 * 3 = 12`. --- #### Question 20 Consider the implementation of an **off-by-one algorithmic flaw** in a 1D array search loop: ```java public static boolean containsTarget(int[] arr, int target) { for (int i = 0; i < arr.length - 1; i++) { if (arr[i] == target) return true; } return false; }Under which condition will this method fail to return the correct result? A) When target is located at index 0. B) When target is located exclusively at the final index (arr.length - 1). C) When the array contains negative numbers. D) When target does not exist in the array.
String s1 = new String("Hello"); String s2 = new String("Hello"); boolean b1 = (s1 == s2); boolean b2 = s1.equals(s2); System.out.println(b1 + " " + b2);
What is the output displayed in the terminal? A) `true true` B) **`false true`** C) `true false` D) `false false` *CORRECT ANSWER:* B) `false true` *RATIONALE:* Using `new String("Hello")` explicitly forces Java to construct two separate `String` objects on the heap with distinct memory addresses. The relational operator `==` compares object references (memory pointers), so `s1 == s2` evaluates to `false`. The `.equals()` method compares the actual character sequences inside the strings, so `s1.equals(s2)` evaluates to `true`. --- #### Question 23 Consider the following recursive method demonstrating a **base case and call stack execution** : ```java public static int mystery(int n) { if (n <= 1) return 1; return n + mystery(n - 1); }What value is returned by the method call mystery(4)?
RATIONALE: Trace the recursive calls step-by-step:
What happens if a recursive method lacks a valid base case or fails to reach it? A) The code will refuse to compile due to missing return branches. B) The program enters infinite recursion, eventually causing a StackOverflowError at runtime. C) The JVM automatically terminates the loop after 100 iterations without throwing an error. D) The return value defaults to 0 or null. CORRECT ANSWER: B) The program enters infinite recursion, eventually causing a StackOverflowError at runtime. RATIONALE: Each recursive call allocates a new frame on the system execution stack to store local variables and parameters. Without a functional base case to break