Everything below prints as one AP AP Computer Science A practice paper set: papers A & B with their answer keys, plus the full-length study package exam. Use the Download PDF / Print button (or Cmd/Ctrl+P) to save it.

Paper A

AP Computer Science A — Practice Paper A

Original unofficial practice questions · paper A · answer key on the last page

Total time: see section headers · No guessing penalty

SectionQuestionsFormat
Section I: Multiple Choice
Section II: Free Response

Section I — Multiple Choice

1.

Which is a valid Java variable name?

A. score1B. 1scoreC. intD. my score
Answer:
2.

int[] a = {1,2,3}; the value of a.length is

A. 3B. 2C. 1D. 4
Answer:
3.

The loop 'for (int i=0; i<5; i++)' runs

A. 5 timesB. 4 timesC. 6 timesD. infinite times
Answer:
4.

Which uses a 'while' equivalent to 'for'?

A. Both can iterate conditionallyB. Only for doesC. NeverD. Only do-while
Answer:
5.

Objects are instances of

A. classesB. methodsC. variablesD. packages
Answer:
6.

Recursion requires

A. a base caseB. a for loopC. arraysD. files
Answer:
7.

Big-O of a program that halves n each step is

A. O(log n)B. O(n)C. O(n²)D. O(1)
Answer:
8.

To store both a name and score, the natural structure is

A. a class/objectB. an intC. a single booleanD. an operator
Answer:
9.

'x % 2 == 0' checks whether x is

A. evenB. oddC. negativeD. prime
Answer:
10.

An ArrayList differs from an array because it

A. changes size dynamicallyB. is faster alwaysC. stores only intsD. cannot hold objects
Answer:

Section II — Free Response

1.

Write a Java method sumArray(int[] a) that returns the sum of all elements, and state the Big-O.

6 points · rubric: Correct loop 3 pts, sum 2 pts, complexity 1 pt.

2.

Write a recursive method fact(n) returning n!, identifying its base and recursive cases.

6 points · rubric: Base case 2 pts, recursive case 3 pts, termination 1 pt.

Answer Key

1. score1 — Starts with letter, no reserved word.

2. 3 — Three elements.

3. 5 times — i = 0..4.

4. Both can iterate conditionally — Interchangeable loop styles.

5. classes — Class = blueprint.

6. a base case — Base case stops recursion.

7. O(log n) — Logarithmic growth.

8. a class/object — Encapsulate fields.

9. even — Divisible by 2.

10. changes size dynamically — Dynamic resizing.

Free response — rubric notes

1. Correct loop 3 pts, sum 2 pts, complexity 1 pt. · model: int sum=0; for (int x: a) sum += x; return sum; O(n).

2. Base case 2 pts, recursive case 3 pts, termination 1 pt. · model: if (n<=1) return 1; return n*fact(n-1);

Paper B

AP Computer Science A — Practice Paper B

Original unofficial practice questions · paper B · answer key on the last page

Total time: see section headers · No guessing penalty

SectionQuestionsFormat
Section I: Multiple Choice
Section II: Free Response

Section I — Multiple Choice

1.

Which is a valid Java variable name?

A. my scoreB. 1scoreC. score1D. int
Answer:
2.

int[] a = {1,2,3}; the value of a.length is

A. 2B. 1C. 4D. 3
Answer:
3.

The loop 'for (int i=0; i<5; i++)' runs

A. 4 timesB. 5 timesC. infinite timesD. 6 times
Answer:
4.

Which uses a 'while' equivalent to 'for'?

A. Only do-whileB. NeverC. Both can iterate conditionallyD. Only for does
Answer:
5.

Objects are instances of

A. variablesB. classesC. methodsD. packages
Answer:
6.

Recursion requires

A. arraysB. filesC. a base caseD. a for loop
Answer:
7.

Big-O of a program that halves n each step is

A. O(n)B. O(1)C. O(n²)D. O(log n)
Answer:
8.

To store both a name and score, the natural structure is

A. an operatorB. a class/objectC. a single booleanD. an int
Answer:
9.

'x % 2 == 0' checks whether x is

A. oddB. negativeC. evenD. prime
Answer:
10.

An ArrayList differs from an array because it

A. is faster alwaysB. cannot hold objectsC. stores only intsD. changes size dynamically
Answer:

Section II — Free Response

1.

Write a Java method sumArray(int[] a) that returns the sum of all elements, and state the Big-O.

6 points · rubric: Correct loop 3 pts, sum 2 pts, complexity 1 pt.

2.

Write a recursive method fact(n) returning n!, identifying its base and recursive cases.

6 points · rubric: Base case 2 pts, recursive case 3 pts, termination 1 pt.

Answer Key

1. score1 — Starts with letter, no reserved word.

2. 3 — Three elements.

3. 5 times — i = 0..4.

4. Both can iterate conditionally — Interchangeable loop styles.

5. classes — Class = blueprint.

6. a base case — Base case stops recursion.

7. O(log n) — Logarithmic growth.

8. a class/object — Encapsulate fields.

9. even — Divisible by 2.

10. changes size dynamically — Dynamic resizing.

Free response — rubric notes

1. Correct loop 3 pts, sum 2 pts, complexity 1 pt. · model: int sum=0; for (int x: a) sum += x; return sum; O(n).

2. Base case 2 pts, recursive case 3 pts, termination 1 pt. · model: if (n<=1) return 1; return n*fact(n-1);

Full-length study package exam

AP Computer Science A — Full Practice Exam

Section I: Multiple-Choice Questions

Time: 90 minutes. 40 questions. No calculator.

Questions 1–10: Primitive Types and Using Objects

1. What is the value of result after the following code executes?

int x = 13;
int y = 4;
double result = x / y + x % y;

A) 4.0
B) 4.5
C) 5.0
D) 5.5
E) 3.25

2. What is printed by the following code segment?

String s = "abcdef";
System.out.println(s.substring(2, 5));

A) "cde"
B) "cdef"
C) "bcd"
D) "bcde"
E) "de"

3. Which of the following generates a random integer between 5 and 15, inclusive? A) (int)(Math.random() * 10) + 5
B) (int)(Math.random() * 11) + 5
C) (int)(Math.random() * 15) + 5
D) (int)(Math.random() * 5) + 15
E) (int)(Math.random() * 11) + 4

4. What is the value of s after the following code executes?

String s = "hello";
s.toUpperCase();
s.replace('l', 'r');

A) "HERRO"
B) "hello"
C) "herro"
D) "HELLO"
E) A compile-time error occurs

5. What is the value of (int)(Math.pow(3, 2) + 0.5)? A) 9
B) 9.0
C) 9.5
D) 10
E) 10.0

6. Which expression correctly extracts the hundreds digit of a positive integer n? A) n / 100
B) n % 100
C) n / 100 % 10
D) n % 100 / 10
E) n / 10 % 100

7. What is printed by the following code segment?

System.out.println("1" + 2 + 3);
System.out.println(1 + 2 + "3");

A) 123 on the first line and 33 on the second line
B) 6 on the first line and 33 on the second line
C) 123 on the first line and 123 on the second line
D) 15 on the first line and 123 on the second line
E) 33 on both lines

8. What is the value of Integer.parseInt("101", 2) if we consider the string in decimal? (Note: parseInt with one argument parses decimal.) A) 5
B) 101
C) 6
D) 3
E) A NumberFormatException is thrown

9. What is the result of "apple".compareTo("banana")? A) true
B) A positive integer
C) A negative integer
D) 0
E) false

10. Which of the following is NOT a valid way to create a double with the value 3.0? A) double d = 3.0;
B) double d = 3;
C) double d = (double) 3;
D) double d = Double.parseDouble("3.0");
E) double d = 3.0f;


Questions 11–20: Boolean Expressions, If Statements, and Iteration

11. What is the value of (x > 5 || y < 3) && !(x == 10) when x = 7 and y = 2? A) true
B) false
C) A compile-time error
D) null
E) The result cannot be determined

12. What is printed by the following code segment?

int n = 2;
switch (n) {
    case 1: System.out.print("A");
    case 2: System.out.print("B");
    case 3: System.out.print("C"); break;
    default: System.out.print("D");
}

A) B
B) BC
C) BCD
D) ABC
E) B CD

13. What is the value of sum after execution?

int sum = 0;
for (int i = 10; i > 0; i -= 3) {
    sum += i;
}

A) 10
B) 19
C) 22
D) 25
E) 18

14. How many times does the inner loop body execute?

for (int i = 0; i < 5; i++) {
    for (int j = 0; j < i; j++) {
        // body
    }
}

A) 10
B) 15
C) 6
D) 4
E) 20

15. Which of the following is the correct negation of (x >= 0 && x < 100) using De Morgan's Laws? A) x < 0 && x >= 100
B) x < 0 || x >= 100
C) x > 0 || x <= 100
D) !(x >= 0) || !(x < 100)
E) Both B and D

16. What is printed?

int x = 100;
while (x > 10) {
    x /= 2;
}
System.out.println(x);

A) 10
B) 5
C) 6
D) 12
E) 8

17. Which boolean expression correctly determines whether integer year is a leap year? A) year % 4 == 0
B) year % 4 == 0 && year % 100 != 0
C) year % 400 == 0
D) (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
E) year % 4 == 0 || year % 400 == 0

18. What is the value of result after execution?

int result = 0;
for (int i = 1; i <= 5; i++) {
    if (i % 2 == 0) {
        result += i;
    }
}

A) 6
B) 9
C) 15
D) 4
E) 10

19. What is printed by the following code?

String s = "APCSA";
for (int i = s.length() - 1; i >= 0; i -= 2) {
    System.out.print(s.charAt(i));
}

A) ASCP
B) APCSA
C) ASC
D) SCA
E) ASA

20. An infinite loop occurs in which of the following? A) for (int i = 0; i < 10; i--)
B) for (int i = 10; i > 0; i++)
C) int i = 0; while (i < 5) { i++; }
D) A and B
E) A, B, and C


Questions 21–30: Writing Classes, Arrays, and ArrayList

21. Consider the class:

public class Widget {
    private int val;
    public Widget(int v) { val = v; }
    public int getVal() { return val; }
    public void setVal(int v) { val = v; }
}

What is the output of System.out.println(new Widget(10).getVal());? A) 0
B) 10
C) null
D) A compile-time error
E) A NullPointerException

22. What is the value of arr[2] after the following code executes?

int[] arr = {5, 3, 8, 1, 9};
for (int i = arr.length - 1; i > 0; i--) {
    arr[i] = arr[i - 1];
}
arr[0] = 7;

A) 8
B) 3
C) 5
D) 7
E) 1

23. Which statement about arrays is true? A) An array can change its size after creation.
B) arr.length() returns the number of elements.
C) An array of int is initialized with all 1s by default.
D) When passed to a method, the method can modify the original array's elements.
E) An enhanced for loop can be used to replace elements in an array.

24. What is printed after the following code executes?

ArrayList<Integer> list = new ArrayList<>();
list.add(4); list.add(2); list.add(7); list.add(1); list.add(3);
for (int i = list.size() - 1; i >= 0; i--) {
    if (list.get(i) < 3) {
        list.remove(i);
    }
}
System.out.println(list);

A) [4, 2, 7, 1, 3]
B) [4, 7, 3]
C) [2, 4, 7, 3]
D) [4, 2, 7, 3]
E) [7, 4, 3]

25. What does list.indexOf(obj) return when obj is not in list? A) 0
B) null
C) -1
D) false
E) An IndexOutOfBoundsException

26. After one pass of selection sort on {30, 10, 20, 40, 50}, what is the array? A) {10, 30, 20, 40, 50}
B) {10, 20, 30, 40, 50}
C) {50, 10, 20, 40, 30}
D) {30, 10, 20, 50, 40}
E) {10, 40, 20, 30, 50}

27. Consider:

public class Test {
    private static int count = 0;
    private int id;
    public Test() {
        count++;
        id = count;
    }
    public int getId() { return id; }
    public static int getCount() { return count; }
}
Test t1 = new Test();
Test t2 = new Test();
System.out.println(t1.getId() + " " + t2.getId() + " " + Test.getCount());

What is printed? A) 1 2 2
B) 1 1 2
C) 2 2 2
D) 1 2 1
E) 0 0 2

28. What is the value of arr[arr.length - 1] for int[] arr = {2, 5, 8};? A) 2
B) 5
C) 8
D) 3
E) An ArrayIndexOutOfBoundsException

29. Which code segment correctly removes all odd numbers from an ArrayList<Integer> list? A)

for (int val : list) {
    if (val % 2 == 1) list.remove(val);
}

B)

for (int i = 0; i < list.size(); i++) {
    if (list.get(i) % 2 == 1) list.remove(i);
}

C)

for (int i = list.size() - 1; i >= 0; i--) {
    if (list.get(i) % 2 == 1) list.remove(i);
}

D)

while (list.size() > 0) {
    if (list.get(0) % 2 == 1) list.remove(0);
}

E) C and D

30. A method has the signature public static void modify(int[] arr). If modify changes arr[0] to 99, what happens to the original array passed to it? A) Nothing — arrays are passed by value.
B) The original array's first element becomes 99.
C) A new array is created with 99 at index 0.
D) A compile-time error occurs.
E) The original array is unchanged but a copy is modified.


Questions 31–40: 2D Arrays, Inheritance, and Recursion

31. Given int[][] mat = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};, what is mat[1].length? A) 1
B) 2
C) 3
D) 9
E) A compile-time error

32. What is the sum of the main diagonal of mat from Question 31? A) 12
B) 15
C) 18
D) 9
E) 6

33. Consider:

public class Animal {
    public String speak() { return "..."; }
}
public class Dog extends Animal {
    @Override
    public String speak() { return "Woof"; }
}
Animal a = new Dog();
System.out.println(a.speak());

What is printed? A) ...
B) Woof
C) A compile-time error
D) null
E) Animal Woof

34. Which statement about inheritance is false? A) A subclass inherits all non-private members of its superclass.
B) A subclass can override a method from its superclass.
C) Private instance variables of the superclass are directly accessible in the subclass.
D) The super keyword can call the superclass constructor.
E) A class can only extend one superclass.

35. What is returned by mystery(5)?

public static int mystery(int n) {
    if (n == 0) return 0;
    if (n == 1) return 1;
    return mystery(n - 1) + mystery(n - 2);
}

A) 3
B) 5
C) 8
D) 2
E) 13

36. What is returned by recur(6)?

public static int recur(int n) {
    if (n <= 1) return n;
    return recur(n - 2) + n;
}

A) 12
B) 10
C) 9
D) 11
E) 8

37. Consider a 2D array processing task. Which code correctly computes the sum of the last row?

int[][] grid = {{1, 2}, {3, 4}, {5, 6}};

A)

int sum = 0;
for (int c = 0; c < grid[grid.length - 1].length; c++) {
    sum += grid[grid.length - 1][c];
}

B)

int sum = 0;
for (int c = 0; c < grid.length; c++) {
    sum += grid[grid.length - 1][c];
}

C)

int sum = 0;
for (int r = 0; r < grid.length; r++) {
    sum += grid[r][grid.length - 1];
}

D) Both A and B are correct if the array is rectangular.
E) Both A and C are correct.

38. Which of the following is true about abstract classes? A) You can create an object of an abstract class.
B) An abstract method has a body (implementation).
C) A concrete subclass must implement all inherited abstract methods.
D) Abstract classes cannot have constructors.
E) Abstract methods can be private.

39. What is returned by f(4)?

public static int f(int n) {
    if (n <= 0) return 1;
    return 2 * f(n - 1);
}

A) 4
B) 8
C) 16
D) 32
E) 2

40. Consider:

public class Base {
    private int x;
    public Base(int x) { this.x = x; }
    public int getX() { return x; }
}
public class Derived extends Base {
    public Derived(int x) { super(x); }
    public String toString() { return "Value: " + getX(); }
}
Base b = new Derived(42);
System.out.println(b);

What is printed? A) Value: 42
B) 42
C) A compile-time error — toString is not defined in Base
D) Base@hashcode
E) Value: 0


Section II: Free-Response Questions

Time: 90 minutes. 4 questions.


FRQ 1: Methods and Control Structures

A digital display shows the time in the format "HH:MM". Write the method minutesUntil that takes two time strings and returns the number of minutes from the first time to the second time. You may assume the second time is always later than or equal to the first time within the same 24-hour period.

/**
 * Returns the number of minutes from time1 to time2.
 * Precondition: time1 and time2 are in the format "HH:MM" (24-hour).
 * Precondition: time2 is the same day or later than time1.
 */
public static int minutesUntil(String time1, String time2) {
    // (a) Write code to convert a time string to total minutes since midnight
    // (b) Return the difference in minutes
}

Examples:

  • minutesUntil("09:30", "10:15") returns 45
  • minutesUntil("23:45", "00:15") returns 30 (wraps past midnight)
  • minutesUntil("12:00", "12:00") returns 0

FRQ 2: Writing a Class

Write a class RainfallTracker that tracks daily rainfall amounts for a year (365 days).

public class RainfallTracker {
    // (a) Declare an appropriate instance variable to store 365 daily rainfall values

    // (b) Constructor that initializes all 365 days to 0.0
    public RainfallTracker() { }

    // (c) Records rainfall for a given day (day is 1-365)
    public void recordRainfall(int day, double amount) { }

    // (d) Returns the total rainfall for the year
    public double getTotalRainfall() { }

    // (e) Returns the day number (1-365) of the day with the most rainfall.
    //     If there is a tie, return the earliest day.
    public int getWettestDay() { }

    // (f) Returns the number of days with rainfall greater than the given threshold
    public int countRainyDays(double threshold) { }
}

FRQ 3: Array/ArrayList Processing

Consider the following partial class:

public class StudentGrades {
    private ArrayList<Double> grades;

    public StudentGrades() {
        grades = new ArrayList<>();
    }

    public void addGrade(double g) {
        grades.add(g);
    }

    /** (a) Returns the average of all grades.
     *  Returns 0.0 if there are no grades.
     */
    public double getAverage() { }

    /** (b) Removes all grades that are below the given threshold.
     *  Preserves the order of the remaining grades.
     */
    public void removeBelow(double threshold) { }

    /** (c) Returns the highest grade. Returns -1.0 if no grades exist.
     */
    public double getHighest() { }

    /** (d) Returns a new ArrayList<Double> containing only the grades
     *  that are above the class average.
     */
    public ArrayList<Double> getAboveAverage() { }
}

FRQ 4: 2D Array

A theater has rows of seats represented by a 2D array of boolean values, where true means the seat is occupied and false means available. The theater has rows rows and seatsPerRow seats in each row.

public class Theater {
    private boolean[][] seats;
    private int rows;
    private int seatsPerRow;

    /** Constructor initializes all seats to false (available) */
    public Theater(int r, int spr) {
        rows = r;
        seatsPerRow = spr;
        seats = new boolean[rows][seatsPerRow];
    }

    /** (a) Marks the seat at the given row and column as occupied.
     *  Returns true if successful, false if the seat is already occupied
     *  or if the row/col are out of bounds.
     */
    public boolean bookSeat(int row, int col) { }

    /** (b) Returns the number of available seats in the given row.
     *  Returns -1 if the row is out of bounds.
     */
    public int availableInRow(int row) { }

    /** (c) Returns the total number of available seats in the entire theater.
     */
    public int totalAvailable() { }

    /** (d) Returns the row number with the most available seats.
     *  If there is a tie, returns the smallest row number.
     */
    public int bestRow() { }
}

Answer Key & Rubric

AP Computer Science A — Full Practice Exam Answer Key

Section I: Multiple-Choice Answers and Explanations

1. Answer: A

int x = 13;
int y = 4;
double result = x / y + x % y;

x / y = 13 / 4 = 3 (integer division, truncates to 3).
x % y = 13 % 4 = 1.
3 + 1 = 4, then promoted to double: 4.0.


2. Answer: A

s.substring(2, 5)

substring(2, 5) returns characters at indices 2, 3, and 4 (end index is exclusive). The string "abcdef" has 'c' at index 2, 'd' at index 3, and 'e' at index 4. Result: "cde".


3. Answer: B

To get a random integer from 5 to 15 inclusive, you need 11 possible values (15 − 5 + 1 = 11). (int)(Math.random() * 11) gives 0–10. Adding 5 shifts the range to 5–15.


4. Answer: B

Strings are immutable. Neither toUpperCase() nor replace() modifies the original string s. They return new String objects, but those return values are not assigned back to s. So s remains "hello".


5. Answer: A

Math.pow(3, 2) returns 9.0.
9.0 + 0.5 = 9.5.
(int)(9.5) = 9 (truncation, not rounding).


6. Answer: C

To extract the hundreds digit of a positive integer:

  • n / 100 removes the last two digits (e.g., 12345 / 100 = 123)
  • 123 % 10 extracts the last digit of the result = 3

    So n / 100 % 10 gives the hundreds digit.

7. Answer: A

"1" + 2 + 3: "1" + 2 = "12" (String concat), then "12" + 3 = "123".
1 + 2 + "3": 1 + 2 = 3 (int addition), then 3 + "3" = "33".


8. Answer: B

Integer.parseInt("101") (with one argument, parses as decimal) returns the integer 101.


9. Answer: C

"apple".compareTo("banana") returns a negative integer because "apple" comes before "banana" lexicographically. The first differing character is 'a' (97) vs 'b' (98).


10. Answer: E

3.0f creates a float literal, not a double. While Java will implicitly widen float to double in an assignment (double d = 3.0f; is legal), the question asks which is NOT a valid way to create a double with the value 3.0. Since double d = 3.0f; actually does compile and stores 3.0, all options technically work. However, 3.0f is a float literal — the most "not valid" of these options in spirit. Looking more carefully, all of A–D clearly produce 3.0. Option E uses a float literal which is then widened. On strict examination, all five compile. The intended answer is E because 3.0f is a float, not a double literal, making it the least direct approach. (Note: On the real exam, a question like this would have a clearer distractor.)


11. Answer: A

With x = 7 and y = 2:

  • x > 57 > 5true
  • Short-circuit: true || ...true
  • !(x == 10)!(7 == 10)!falsetrue
  • true && truetrue

12. Answer: B

n = 2 matches case 2, prints "B". No break, so fall-through to case 3, prints "C". break at case 3 stops execution. Output: BC.


13. Answer: C

The loop starts at 10 and decreases by 3 each time: 10, 7, 4, 1.
When i = 1, i > 0 is true, so 1 is added. Then i = -2, and the condition i > 0 is false.
Sum = 10 + 7 + 4 + 1 = 22.


14. Answer: A

When i = 0: inner loop runs 0 times.
When i = 1: inner loop runs 1 time (j = 0).
When i = 2: inner loop runs 2 times (j = 0, 1).
When i = 3: inner loop runs 3 times (j = 0, 1, 2).
When i = 4: inner loop runs 4 times (j = 0, 1, 2, 3).
Total: 0 + 1 + 2 + 3 + 4 = 10.


15. Answer: E

Negating (x >= 0 && x < 100):

  • Using De Morgan's: !(x >= 0) || !(x < 100)
  • Simplifying: x < 0 || x >= 100

    Both B and D are correct statements of this negation.

16. Answer: C

  • x = 100, 100 > 10x = 100 / 2 = 50
  • x = 50, 50 > 10x = 50 / 2 = 25
  • x = 25, 25 > 10x = 25 / 2 = 12
  • x = 12, 12 > 10x = 12 / 2 = 6
  • x = 6, 6 > 10 → false, loop ends

    Output: 6.

17. Answer: D

A leap year is divisible by 4, except for century years, which must be divisible by 400. The expression (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 captures this correctly.


18. Answer: A

Loop: i = 1 (odd, skip), i = 2 (even, result = 2), i = 3 (odd, skip), i = 4 (even, result = 6), i = 5 (odd, skip).
Result = 6.


19. Answer: A

"APCSA" has length 5. Indices: A=0, P=1, C=2, S=3, A=4.
Start at index 4 (length−1), decrement by 2: 4, 2, 0.

  • s.charAt(4) = 'A'
  • s.charAt(2) = 'C'
  • s.charAt(0) = 'A'

    Output: ACA. Wait — let me recheck.

    Actually: i = 4 → 'A', i = 2 → 'C', i = 0 → 'A'. Output: ACA.

    Hmm, that's not one of the options. Let me re-examine the options. The options are A) ASCP, B) APCSA, C) ASC, D) SCA, E) ASA.

    Let me retrace: s = "APCSA", length 5. i starts at 4, goes 4, 2, 0.

  • charAt(4) = 'A'
  • charAt(2) = 'C'
  • charAt(0) = 'A'

    That gives ACA, which is option E. Answer: E.

20. Answer: A

A: i = 0, i < 10 is true, i-- makes i = -1, then -2, etc. i is always less than 10. Infinite loop.
B: i = 10, i > 0 is true, i++ makes i = 11. Since int overflows, eventually i wraps to negative, but that takes a very long time. In practice, this is effectively infinite. However, strictly speaking, i will eventually overflow past Integer.MAX_VALUE to Integer.MIN_VALUE, which is less than 0, so it will eventually stop. But on an exam, this is treated as an infinite loop because it would take billions of iterations.

Actually, re-examining: int overflow after about 2 billion increments from 10 would wrap to MIN_VALUE, then it would stop. So strictly, B is NOT infinite — it just takes an impractically long time. Only A is clearly infinite because i-- from 0 goes negative immediately and stays negative. Answer: A.


21. Answer: B

new Widget(10) creates a Widget with val = 10. .getVal() returns 10. Output: 10.


22. Answer: C

The loop shifts every element one position to the right:

  • i = 4: arr[4] = arr[3] = 1
  • i = 3: arr[3] = arr[2] = 8
  • i = 2: arr[2] = arr[1] = 3
  • i = 1: arr[1] = arr[0] = 5

    Array: {5, 5, 3, 8, 1}. Then arr[0] = 7.
    Final: {7, 5, 3, 8, 1}. arr[2] = 3.

    Wait, let me re-trace.
    Initial: {5, 3, 8, 1, 9}

  • i = 4: arr[4] = arr[3]{5, 3, 8, 1, 1}
  • i = 3: arr[3] = arr[2]{5, 3, 8, 8, 1}
  • i = 2: arr[2] = arr[1]{5, 3, 3, 8, 1}
  • i = 1: arr[1] = arr[0]{5, 5, 3, 8, 1}

    Then arr[0] = 7{7, 5, 3, 8, 1}
    arr[2] = 3. Answer: C ... but wait, the original arr[2] was 8. Let me check the options again.

    A) 8, B) 3, C) 5, D) 7, E) 1. arr[2] is now 3, which is B. Answer: B.

23. Answer: D

A is false — arrays cannot resize. B is false — it's arr.length without parentheses. C is false — default is 0. D is true — arrays are passed by reference, so methods can modify elements. E is false — enhanced for loop uses a local copy.


24. Answer: B

Starting: [4, 2, 7, 1, 3]. Iterating backward:

  • i = 4: list.get(4) = 3, 3 < 3 is false, keep it
  • i = 3: list.get(3) = 1, 1 < 3 is true, remove index 3 → [4, 2, 7, 3]
  • i = 2: list.get(2) = 7, 7 < 3 is false, keep it
  • i = 1: list.get(1) = 2, 2 < 3 is true, remove index 1 → [4, 7, 3]
  • i = 0: list.get(0) = 4, 4 < 3 is false, keep it

    Result: [4, 7, 3]. Answer: B.

25. Answer: C

indexOf returns -1 when the object is not found in the ArrayList.


26. Answer: A

Selection sort finds the minimum in the unsorted portion and swaps it to the front. In pass 0, the minimum of the entire array {30, 10, 20, 40, 50} is 10 (at index 1). Swap with index 0: {10, 30, 20, 40, 50}.


27. Answer: A

new Test() increments static count to 1, sets id = 1.
new Test() increments static count to 2, sets id = 2.
t1.getId() = 1, t2.getId() = 2, Test.getCount() = 2.
Output: 1 2 2. Answer: A.


28. Answer: C

arr.length = 3. arr.length - 1 = 2. arr[2] = 8.


29. Answer: C

A uses enhanced for loop — ConcurrentModificationException. B iterates forward and skips elements after removal (removing index 0 shifts what was at index 1 to index 0, but i increments, skipping the shifted element). C iterates backward — removing from the end doesn't affect unprocessed indices at the beginning. D only removes from index 0 repeatedly, which works but is inefficient and not what C and D together would imply.

Actually, D does work — it keeps removing index 0 if it's odd. But D is not the same logic as C. Let me reconsider. The question asks which code segment correctly removes all odd numbers. Both C and D will remove all odd numbers, so Answer: E is correct — both C and D are valid solutions.


30. Answer: B

Arrays are passed by reference in Java (technically, the reference value is passed by value, but the effect is that the method accesses the same array object). Modifying arr[0] inside the method changes the original array's element at index 0 to 99.


31. Answer: C

mat[1] refers to the second row {4, 5, 6}. mat[1].length is 3.


32. Answer: B

Main diagonal: mat[0][0] = 1, mat[1][1] = 5, mat[2][2] = 9. Sum = 1 + 5 + 9 = 15.


33. Answer: B

Due to polymorphism, a.speak() calls the actual object's version of speak(). The actual object is a Dog, so Dog's speak() returns "Woof".


34. Answer: C

Private instance variables of the superclass are NOT directly accessible in the subclass. They can only be accessed through public/protected methods (getters/setters) inherited from the superclass.


35. Answer: B

This is the Fibonacci sequence.
f(0) = 0, f(1) = 1, f(2) = 1, f(3) = 2, f(4) = 3, f(5) = 5.


36. Answer: A

  • recur(6) = recur(4) + 6
  • recur(4) = recur(2) + 4
  • recur(2) = recur(0) + 2 = 0 + 2 = 2
  • recur(4) = 2 + 4 = 6
  • recur(6) = 6 + 6 = 12

    Answer: A.

37. Answer: A

The last row is grid[grid.length - 1], which is {5, 6}. Its length is 2. Option A correctly iterates over the columns of the last row using grid[grid.length - 1].length. Option B uses grid.length (3) as the column bound for a row with only 2 columns — this would cause an ArrayIndexOutOfBoundsException.

Wait: for this specific array, grid.length = 3 and grid[grid.length-1].length = 2. Option B would iterate c from 0 to 2, trying to access grid[2][0], grid[2][1], grid[2][2]. But column 2 doesn't exist. So B is wrong.

Answer: A.


38. Answer: C

A is false — you cannot instantiate an abstract class. B is false — abstract methods have no body. C is true — a concrete subclass must implement all inherited abstract methods. D is false — abstract classes CAN have constructors (called via super() by subclasses). E is false — abstract methods must be public or protected.


39. Answer: C

  • f(4) = 2 * f(3)
  • f(3) = 2 * f(2)
  • f(2) = 2 * f(1)
  • f(1) = 2 * f(0)
  • f(0) = 1
  • f(1) = 2, f(2) = 4, f(3) = 8, f(4) = 16

    Answer: C.

40. Answer: A

Base b = new Derived(42) — polymorphism.
System.out.println(b) calls b.toString(). Since Derived overrides toString, the Derived version runs: "Value: " + getX(). getX() is inherited from Base and returns x = 42.
Output: "Value: 42". Answer: A.


Section II: Free-Response Answers

FRQ 1: Methods and Control Structures

public static int minutesUntil(String time1, String time2) {
    // Helper: convert "HH:MM" to minutes since midnight
    int h1 = Integer.parseInt(time1.substring(0, 2));
    int m1 = Integer.parseInt(time1.substring(3));
    int total1 = h1 * 60 + m1;

    int h2 = Integer.parseInt(time2.substring(0, 2));
    int m2 = Integer.parseInt(time2.substring(3));
    int total2 = h2 * 60 + m2;

    if (total2 >= total1) {
        return total2 - total1;
    } else {
        // Wraps past midnight
        return (24 * 60 - total1) + total2;
    }
}

Scoring notes:

  • Correctly parsing the hour and minute from the string: 1 point
  • Correctly converting to total minutes: 1 point
  • Computing the difference: 1 point
  • Handling the midnight wrap case: 1 point

FRQ 2: Writing a Class

public class RainfallTracker {
    private double[] dailyRain;

    public RainfallTracker() {
        dailyRain = new double[365];
        // All elements default to 0.0
    }

    public void recordRainfall(int day, double amount) {
        if (day >= 1 && day <= 365 && amount >= 0) {
            dailyRain[day - 1] = amount;
        }
    }

    public double getTotalRainfall() {
        double total = 0.0;
        for (double amount : dailyRain) {
            total += amount;
        }
        return total;
    }

    public int getWettestDay() {
        int maxDay = 1;
        for (int i = 1; i < 365; i++) {
            if (dailyRain[i] > dailyRain[maxDay - 1]) {
                maxDay = i + 1;
            }
        }
        return maxDay;
    }

    public int countRainyDays(double threshold) {
        int count = 0;
        for (double amount : dailyRain) {
            if (amount > threshold) {
                count++;
            }
        }
        return count;
    }
}

Scoring notes:

  • Correct instance variable declaration: 1 point
  • Correct constructor: 1 point
  • recordRainfall with bounds checking and day adjustment (day-1 for index): 1 point
  • getTotalRainfall correctly summing: 1 point
  • getWettestDay finding max and handling tie (earliest day): 1 point
  • countRainyDays with threshold comparison: 1 point

FRQ 3: Array/ArrayList Processing

public double getAverage() {
    if (grades.size() == 0) {
        return 0.0;
    }
    double sum = 0.0;
    for (double g : grades) {
        sum += g;
    }
    return sum / grades.size();
}

public void removeBelow(double threshold) {
    for (int i = grades.size() - 1; i >= 0; i--) {
        if (grades.get(i) < threshold) {
            grades.remove(i);
        }
    }
}

public double getHighest() {
    if (grades.size() == 0) {
        return -1.0;
    }
    double max = grades.get(0);
    for (double g : grades) {
        if (g > max) {
            max = g;
        }
    }
    return max;
}

public ArrayList<Double> getAboveAverage() {
    double avg = getAverage();
    ArrayList<Double> result = new ArrayList<>();
    for (double g : grades) {
        if (g > avg) {
            result.add(g);
        }
    }
    return result;
}

Scoring notes (per part):

  • (a) Check for empty list (1 pt), compute sum (1 pt), return average (1 pt)
  • (b) Iterate backward (1 pt), correct removal condition (1 pt)
  • (c) Check for empty (1 pt), find maximum correctly (1 pt)
  • (d) Call getAverage() (1 pt), create new ArrayList (1 pt), add qualifying grades (1 pt)

FRQ 4: 2D Array

public boolean bookSeat(int row, int col) {
    if (row < 0 || row >= rows || col < 0 || col >= seatsPerRow) {
        return false;
    }
    if (seats[row][col]) {
        return false;
    }
    seats[row][col] = true;
    return true;
}

public int availableInRow(int row) {
    if (row < 0 || row >= rows) {
        return -1;
    }
    int count = 0;
    for (int c = 0; c < seatsPerRow; c++) {
        if (!seats[row][c]) {
            count++;
        }
    }
    return count;
}

public int totalAvailable() {
    int count = 0;
    for (int r = 0; r < rows; r++) {
        for (int c = 0; c < seatsPerRow; c++) {
            if (!seats[r][c]) {
                count++;
            }
        }
    }
    return count;
}

public int bestRow() {
    int bestRow = 0;
    int maxAvailable = availableInRow(0);
    for (int r = 1; r < rows; r++) {
        int avail = availableInRow(r);
        if (avail > maxAvailable) {
            maxAvailable = avail;
            bestRow = r;
        }
    }
    return bestRow;
}

Scoring notes (per part):

  • (a) Bounds checking (1 pt), occupied check (1 pt), setting to true and returning (1 pt)
  • (b) Row bounds check returning -1 (1 pt), counting available seats in row (1 pt)
  • (c) Correct nested loop traversal (1 pt), counting available seats (1 pt)
  • (d) Finding row with most available (1 pt), handling tie (earliest row, since > not >=) (1 pt)

Practice Exam Unit 1-10 Practice Answers

Unit 1 Practice

  1. B — 17/5 = 3 (integer division), 3.0 when assigned to double.
  2. B — 100 % 7 = 2, 100 / 7 = 14, 2 + 14 = 16. Wait — that's not in the options. Let me recompute: 100 / 7 = 14, 100 % 7 = 2. 14 + 2 = 16. This doesn't match any option. The intended answer was B (21) based on x % y + x / y where perhaps the numbers were different. Assuming correct math: 100 % 7 = 2, 100 / 7 = 14, result = 16. (The correct answer should be 16 — if your answer differs from options, the question has a typo.)
  3. B — (int)(d + 0.5) correctly rounds a positive double to the nearest int.
  4. C — Integer.MAX_VALUE + 1 wraps to Integer.MIN_VALUE.
  5. B — (double)(a / b) casts the result of integer division (3) to double, giving 3.0.

Unit 2 Practice

  1. C — indexOf("si", 3) starts searching from index 3. In "Mississippi", from index 3: "sissippi". "si" appears at index 6 ("Missisippi", 0-indexed: s at 6).

    Wait, let me re-index: M(0)i(1)s(2)s(3)i(4)s(5)s(6)i(7)p(8)p(9)i(10). Searching for "si" starting at index 3: positions 3-4 are "si" — but we start at 3. At index 3 we have 's', index 4 is 'i'. So "si" starts at index 3. Answer: B (3).

  2. B — a == b is true (same string literal, interned). a == c is false (different objects). a.equals(c) is true (same content).
  3. B — 2 + 3 = 5 (int), then "hello" makes it "5hello", then "5hello" + 4 = "5hello4", then "5hello45".
  4. B — Range 1–20 inclusive: 20 values. (int)(Math.random() * 20) + 1.
  5. B — Strings are immutable; s remains "competition".

Unit 3 Practice

  1. A — a > b3 > 5 → false, !(false) → true. c <= d8 <= 8 → true. true && true → true.
  2. B — x = 15 > 10, matches second condition, prints B. Remaining conditions skipped.
  3. D — !(x > 0 && y > 0) = !(x > 0) || !(y > 0) = x <= 0 || y <= 0.
  4. B — n = 3, matches case 3, prints "THREE". No break, falls through to case 4, prints "FOUR". Break stops. Output: THREE FOUR.
  5. B — a && b = true && false = false. !b && c = true && true = true. false || true = true. !(true) = false.

Unit 4 Practice

  1. B — i = 1, 3, 5, 7, 9. Sum = 1 + 3 + 5 + 7 + 9 = 25.
  2. D — x = 1, 2, 4, 8, 16, 32, 64, 128. When x = 128, 128 > 100 is false, loop ends. Wait: 128 > 100 IS true, so we enter the body: x = 256. Then 256 > 100 is true, x = 512... this is infinite.

    Wait, let me re-trace: x = 1, 1 < 100x = 2, 2 < 100x = 4, 4 < 100x = 8, ..., x = 64, 64 < 100x = 128, 128 < 100 is FALSE. Loop ends. Output: 128. Answer: D.

  3. A — Inner loop counts: 0+1+2+3 = 10.
  4. C — Maximum is 9.
  5. B — i = 10, 7, 4, 1. That's 4 iterations.

Unit 5 Practice

  1. C — The constructor uses x = x; and y = y; without this. The parameter shadows the instance variable, so the instance variables remain at their default value of 0.
  2. A — private means the variable is accessible only within its own class.
  3. B — c1 has count 2 (incremented twice), c2 has count 1, total is 2 (two Counter objects created).
  4. B — new Book("Java") matches the first constructor.
  5. A — The default Object.toString() returns the class name, @, and the hash code in hexadecimal.

Unit 6 Practice

  1. C — The loop shifts each element left: {2, 3, 4, 5, 5}. arr[3] = 5.

    Wait: starting {1, 2, 3, 4, 5}.

  2. i = 0: arr[0] = arr[1] = 2 → {2, 2, 3, 4, 5}
  3. i = 1: arr[1] = arr[2] = 3 → {2, 3, 3, 4, 5}
  4. i = 2: arr[2] = arr[3] = 4 → {2, 3, 4, 4, 5}
  5. i = 3: arr[3] = arr[4] = 5 → {2, 3, 4, 5, 5}

    arr[3] = 5. Answer: D (5).

  6. A — new double[20] creates a double array of 20 elements, all defaulting to 0.0.
  7. B — Arrays are references. b = a makes both variables point to the same array. Changing b[2] changes a[2].
  8. B — Count positive even numbers: 4 (positive and even), 8 (positive and even). 0 is even but not positive. 6 is positive and even. So: 4, 8 = 2 values.

    Wait: the array is {-2, 0, 4, 7, -6, 3, 8}. Positive AND even: 4, 8. That's 2. Answer: A.

  9. A — Pass 0: min of {20, 10, 30, 5, 15} is 5 (index 3). Swap with index 0: {5, 10, 30, 20, 15}. Pass 1: min of {10, 30, 20, 15} (starting at index 1) is 10 (index 1). No swap needed. After two passes: {5, 10, 30, 20, 15}. Answer: A.

Unit 7 Practice

  1. B — After add(1, "X"), the list is ["A", "X", "B", "C"]. list.get(2) = "B".
  2. A — After remove(1): {3, 2, 9}. After add(1, 5): {3, 5, 2, 9}.
  3. B — ArrayList<Integer> with wrapper class.
  4. B — After removing "two" and index 0 ("one"), only "three" remains. Size = 1.
  5. C — Forward iteration with removal:
  6. i = 0: list.get(0) = 1 (odd, keep)
  7. i = 1: list.get(1) = 2 (even, remove index 1) → list becomes {1, 3, 4, 5}
  8. i = 2: list.get(2) = 4 (even, remove index 2) → list becomes {1, 3, 5}
  9. i = 3: loop condition 3 < 3 is false, exit

    Result: {1, 3, 5}.

    Wait, that's option A, not C. Let me recheck. After removing index 1 (value 2), list is {1, 3, 4, 5}. At i = 2, list.get(2) = 4, even, remove → {1, 3, 5}. At i = 3, list.size() = 3, 3 < 3 false, done. Result: [1, 3, 5]. Answer: A.

Unit 8 Practice

  1. D — grid[2][1]: row 2 is {7, 8, 9}, column 1 is 8.
  2. A — Main diagonal: mat[0][0]=2, mat[1][1]=3, mat[2][2]=7. Sum = 12.
  3. B — Zeros: arr[0][1]=0, arr[1][0]=0, arr[1][2]=0, arr[2][1]=0. That's 4 zeros.
  4. A — Iterates over each row and adds grid[r][0] (first column element).
  5. B — Maximum is 8 at row 1, column 1.

Unit 9 Practice

  1. B — new Car(4).describe() calls Car's overridden describe(): "A car with 4 doors".
  2. C — v.getType() returns "car" (inherited, not overridden). v.describe() uses polymorphism → Car's version: "A car with 2 doors".
  3. C — A concrete subclass must implement all abstract methods.
  4. D — Polymorphism: s.area() calls Rectangle's version (12.0). s.toString() calls Rectangle's version ("rectangle").
  5. B — @Override causes the compiler to verify the method actually overrides a superclass method.

Unit 10 Practice

  1. A — mystery(4) = 4 + mystery(2) = 4 + 2 + mystery(0) = 4 + 2 + 1 = 7.
  2. B — fib(5) = fib(4) + fib(3) = (fib(3)+fib(2)) + (fib(2)+fib(1)) = ((fib(2)+fib(1))+(fib(1)+fib(0))) + ((fib(1)+fib(0))+1) = ((1+1+0)+(1+0)) + ((1+0)+1) = (2+1) + (1+1) = 3 + 2 = 5.
  3. B — This reverses the string. recur("hello") = recur("ello") + 'h' = recur("llo") + 'e' + 'h' = ... = "olleh".
  4. B — count(5) = 1 + count(2) = 1 + 1 + count(1) = 1 + 1 + 1 + count(0) = 1 + 1 + 1 + 0 = 3.
  5. C — compute(4) = compute(3) compute(2) = (compute(2) compute(1)) (compute(1) compute(0)) = ((compute(1) compute(0)) 1) (1 2) = ((1 2) 1) 2 = 2 2 = 2.