← AP Prep

AP Computer Science A Practice Test

Instructions: This free practice test has 16 multiple-choice questions from our full-length AP Computer Science A practice tests. You will have 35 minutes, the same pace as the real exam.

It runs in the same test engine as our full-length tests: you can mark questions for review, cross out choices and move back and forth until time expires. When you finish, you will see every answer with a full explanation. No account needed.

Or

Go Back

All 16 questions, with answers

Every question in this AP Computer Science A practice test is below. The answer and its explanation stay closed until you open them, so you can work each one first.

Question 1

Consider the following code segment.

String result = "";
for (int i = 1; i <= 5; i++)
{
  result += i;
}
System.out.println(result);
Which of the following best describes the behavior of the code segment?
  • AIt prints the sum of the integers from 1 to 5.
  • BIt prints each integer from 1 to 5 on a separate line.
  • CIt prints the string "54321" by concatenating the integers 5 through 1.
  • DIt prints the string "12345" by concatenating the integers 1 through 5.
Show answer and explanation

Answer: D

The variable result is a String initialized to the empty string. The for loop iterates with i from 1 to 5 inclusive. On each iteration, the integer i is concatenated to the string result using the += operator. Since result is a String, the integer i is converted to its string representation before concatenation. After all iterations, result is "12345". The code constructs a string by appending each integer in ascending order.

Question 2

The following method is intended to return the number of vowels (a, e, i, o, u) in a given string. Assume all characters in str are lowercase letters.

public static int countVowels(String str)
{
  int count = 0;
  String vowels = "aeiou";
  for (int i = 0; i < str.length(); i++)
  {
    /* missing code */
  }
  return count;
}
Which of the following can replace /* missing code */ so that the method works as intended?
  • Aif (vowels.indexOf(str) >= 0) { count++; }
  • Bif (vowels.indexOf(str.substring(i, i + 1)) >= 0) { count++; }
  • Cif (str.indexOf(vowels.substring(i, i + 1)) >= 0) { count++; }
  • Dif (str.substring(i, i + 1).equals(vowels)) { count++; }
Show answer and explanation

Answer: B

The method needs to check each character of str against the vowel string. The expression str.substring(i, i + 1) extracts the single character at position i as a one-character string. Then vowels.indexOf(that character) returns a non-negative value if the character is found in "aeiou". Searching for the entire string str within vowels would not check individual characters. Searching for vowels characters within str checks the wrong direction. Comparing a single character to the entire vowels string with equals would never be true.

Question 3

Consider the following class.

public class Fraction
{
  private int num;
  private int den;

  public Fraction(int num, int den)
  {
    this.num = num;
    this.den = den;
  }

  public int getNum() { return num; }
  public int getDen() { return den; }

  public Fraction multiply(Fraction other)
  {
    int newNum = this.num * other.num;
    int newDen = this.den * other.den;
    return new Fraction(newNum, newDen);
  }
}
Fraction f1 = new Fraction(2, 3);
Fraction f2 = new Fraction(4, 5);
Fraction f3 = f1.multiply(f2);
System.out.println(f3.getNum() + "/" + f3.getDen());
What is printed as a result of executing this code segment?
  • A2/3
  • B8/15
  • C6/8
  • D4/5
Show answer and explanation

Answer: B

The Fraction f1 has num=2, den=3. The Fraction f2 has num=4, den=5. The multiply method creates a new Fraction with newNum = 2 * 4 = 8 and newDen = 3 * 5 = 15. The returned Fraction f3 has num=8 and den=15. The println statement outputs 8 followed by / followed by 15, giving 8/15.

Question 4

The following method is intended to shift all elements in an array one position to the right, with the last element wrapping around to position 0.

public static void shiftRight(int[] arr)
{
  for (int i = arr.length - 1; i > 0; i--)
  {
    arr[i] = arr[i - 1];
  }
}

The method does not work as intended. For example, when called with the array {1, 2, 3, 4}, the method produces {1, 1, 2, 3} instead of the expected {4, 1, 2, 3}.
The method does not work as intended. For example, when called with the array {1, 2, 3, 4}, the method produces {1, 1, 2, 3} instead of the expected {4, 1, 2, 3}.

Which of the following changes can be made so that the method works as intended?
  • AChange the loop to start at i = 0 and go to i < arr.length - 1, incrementing i
  • BBefore the loop, store arr[arr.length - 1] in a temporary variable, then after the loop, assign the temporary variable to arr[0]
  • CChange arr[i] = arr[i - 1] to arr[i - 1] = arr[i]
  • DChange the loop condition from i > 0 to i >= 0
Show answer and explanation

Answer: B

The current method shifts elements right correctly by copying each element from position i-1 to position i, working from right to left. However, it loses the last element because the first copy (arr[arr.length-1] = arr[arr.length-2]) overwrites the original last value before it can be placed at index 0. The fix is to save the last element in a temporary variable before the loop starts, then assign it to arr[0] after the loop completes. Changing the loop direction or reversing the assignment would shift left instead of right.

Question 5

Consider the following class.

public class Pet
{
  private String name;
  private int age;

  public Pet(String n, int a)
  {
    name = n;
    age = a;
  }

  public String getName()
  { return name; }

  public int getAge()
  { return age; }
}
Pet p = new Pet("Luna", 3);
System.out.println(p.getName() + " is " + p.getAge());
What is printed as a result of executing this code segment?
  • ALuna is Luna
  • Bnull is 0
  • CPet is 3
  • DLuna is 3
Show answer and explanation

Answer: D

The constructor receives "Luna" as n and 3 as a, assigning them to the instance variables name and age. When getName() is called, it returns "Luna". When getAge() is called, it returns 3. String concatenation produces "Luna is 3". The age value is automatically converted to a string during concatenation.

Question 6

A programmer is using a library that provides the following class.

public class TextFormatter
{
  public TextFormatter(String text)
  { /* implementation not shown */ }

  public String toUpperCase()
  { /* implementation not shown */ }

  public String removeSpaces()
  { /* implementation not shown */ }

  public int countWords()
  { /* implementation not shown */ }
}
Which of the following best describes the purpose of the TextFormatter class?
  • AIt stores a text string and provides methods to transform and analyze it.
  • BIt stores multiple strings and provides methods to sort them.
  • CIt reads text from a file and stores it as an array of words.
  • DIt generates random text strings of a specified length.
Show answer and explanation

Answer: A

The constructor takes a single String parameter, suggesting the class stores text. The methods toUpperCase(), removeSpaces(), and countWords() all operate on text to transform or analyze it. There is no evidence of file reading, sorting multiple strings, or random generation. The class encapsulates a text string and provides utility methods for its manipulation and analysis.

Question 7

Consider the following method. The method is intended to return a new string with all occurrences of target removed from str. For example, removeAll("abcabc", "bc") should return "aa".

public static String removeAll(String str, String target)
{
  /* missing code */
  return str;
}
Which of the following can replace /* missing code */ so that the method works as intended?
  • Awhile (str.indexOf(target) >= 0) { int idx = str.indexOf(target); str = str.substring(0, idx) + str.substring(idx + target.length()); }
  • Bwhile (str.indexOf(target) >= 0) { int idx = str.indexOf(target); str = str.substring(0, idx) + str.substring(idx + 1); }
  • Cwhile (str.indexOf(target) > 0) { int idx = str.indexOf(target); str = str.substring(0, idx) + str.substring(idx + target.length()); }
  • Dint idx = str.indexOf(target); str = str.substring(0, idx) + str.substring(idx + target.length());
Show answer and explanation

Answer: A

The correct approach repeatedly finds the target using indexOf and rebuilds the string by concatenating the part before the target with the part after the target. The portion after the target starts at idx + target.length() to skip the entire target string. Using idx + 1 only removes the first character of the target. Using indexOf(target) > 0 instead of >= 0 fails when the target appears at index 0. Performing the removal only once misses subsequent occurrences.

Question 8

Consider the following class.

public class Student
{
  private String name;
  private int grade;
  private double gpa;

  public Student(String n, int g)
  {
    name = n;
    grade = g;
    gpa = 0.0;
  }

  public String getName()
  { return name; }

  public int getGrade()
  { return grade; }

  public double getGpa()
  { return gpa; }
}
Student s = new Student("Maya", 11);
System.out.println(s.getName() + " " + s.getGrade() + " " + s.getGpa());
What is printed as a result of executing this code segment?
  • AMaya 11 null
  • Bnull 0 0.0
  • CMaya 0 0.0
  • DMaya 11 0.0
Show answer and explanation

Answer: D

The constructor takes "Maya" as n and 11 as g. It assigns name = "Maya", grade = 11, and initializes gpa = 0.0 as a default. The accessor methods return each field's value: getName() returns "Maya", getGrade() returns 11, and getGpa() returns 0.0. String concatenation joins them with spaces, producing "Maya 11 0.0".

Question 9

Consider the following code segment.

int a = 10;
int b = 5;
int c = 3;
boolean result = (a >= b) && (b != c) || (c <= 0);
What is the value of result after executing this code segment?
  • Atrue
  • Bfalse
  • CA compile-time error occurs because the expression mixes && and || operators.
  • DA run-time error occurs during evaluation.
Show answer and explanation

Answer: A

Evaluating with operator precedence where && binds more tightly than ||: first, (a >= b) evaluates to true (10 >= 5). Then (b != c) evaluates to true (5 != 3). The && yields true && true = true. Next, (c <= 0) evaluates to false (3 <= 0). Finally, true || false = true. The value of result is true. Mixing && and || in one expression is valid Java syntax.

Question 10

The following method is intended to return true only when exactly two out of three boolean parameters are true.

public static boolean exactlyTwo(boolean a, boolean b, boolean c)
{
  return /* missing code */;
}
Which of the following expressions can replace /* missing code */ so that exactlyTwo works as intended?
  • A(a && b) || (b && c) || (a && c)
  • B(a && b && !c) || (a && !b && c) || (!a && b && c)
  • C(a || b) && (b || c) && (a || c)
  • Da ^ b ^ c
Show answer and explanation

Answer: B

The method should return true when exactly two of the three parameters are true. The correct approach explicitly enumerates all three such cases: a and b are true but c is false, a and c are true but b is false, or b and c are true but a is false. Simply checking if at least two are true (including all three) overcounts. Using XOR returns true when an odd number of parameters are true (one or three), not exactly two.

Question 11

Consider the following code segment.

int[] nums = {10, 20, 30, 40, 50};
int sum = 0;
for (int val : nums)
{
  if (val > 20)
  {
    sum += val;
  }
}
System.out.println(sum);
What is printed as a result of executing this code segment?
  • A100
  • B120
  • C150
  • D50
Show answer and explanation

Answer: B

The enhanced for loop visits each element. The condition val > 20 is satisfied by 30, 40, and 50 (the values 10 and 20 do not satisfy it since 20 is not strictly greater than 20). The sum is 30 + 40 + 50 = 120. Students who use >= instead of > would include 20 and get 140, while students who sum all elements would get 150.

Question 12

A company tracks customer purchases and uses an algorithm to generate personalized product recommendations. The algorithm uses purchase history, browsing patterns, and demographic data including age, gender, and location.

Which of the following is the most significant privacy concern with this practice?
  • AThe algorithm may recommend products that customers do not want to purchase.
  • BCombining purchase history, browsing patterns, and demographic data creates a detailed personal profile that could be misused if the data is shared or breached.
  • CThe algorithm requires a large amount of computing power to process all the data.
  • DCustomers might receive too many notifications about recommended products.
Show answer and explanation

Answer: B

The most significant privacy concern is the creation of detailed personal profiles by combining multiple types of sensitive data. If this aggregated data is shared with unauthorized parties or exposed through a security breach, it poses serious risks to customer privacy. Unwanted recommendations and excessive notifications are usability issues, not privacy concerns. Computing power requirements are technical considerations unrelated to privacy and responsible computing.

Question 13

The following method is intended to determine whether the string sub appears as a subsequence of the string main. A subsequence means the characters of sub appear in main in the same order, but not necessarily consecutively.

public static boolean isSubsequence(String main, String sub)
{
  int j = 0;
  for (int i = 0; i < main.length() && j < sub.length(); i++)
  {
    /* missing code */
  }
  return j == sub.length();
}
For example, isSubsequence("abcde", "ace") returns true and isSubsequence("abcde", "aec") returns false.

Which of the following can replace /* missing code */ so that the method works as intended?
  • Aif (main.substring(i, i + 1).equals(sub.substring(j, j + 1))) { j++; }
  • Bif (main.substring(i, i + 1).equals(sub.substring(j, j + 1))) { i++; j++; }
  • Cif (main.indexOf(sub.substring(j, j + 1)) >= 0) { j++; }
  • Dif (main.substring(i).equals(sub.substring(j))) { j++; }
Show answer and explanation

Answer: A

The method uses two pointers: i scans through main, and j scans through sub. When the character at position i in main matches the character at position j in sub, j is advanced. The for loop already advances i each iteration, so only j needs to be incremented inside the if statement. Incrementing i an extra time causes characters to be skipped. Using indexOf on the entire remaining main string does not respect ordering. Comparing entire remaining substrings rather than individual characters is also incorrect.

Question 14

Consider the following class.

public class Counter
{
  private int value;

  public Counter()
  {
    value = 0;
  }

  public void increment(int value)
  {
    value = value + 1;  // line 12
  }

  public int getValue()
  {
    return value;
  }
}
Counter c = new Counter();
c.increment(5);
System.out.println(c.getValue());
The output is 0. The programmer expected the output to be 1. Which of the following explains the error and provides a correct fix?
  • AThe parameter should be removed. Replace line 12 with value++;
  • BThe constructor should initialize value to 1 instead of 0.
  • COn line 12, value refers to the parameter, not the instance variable. Replace line 12 with this.value = this.value + 1;
  • DThe method should return an int. Replace line 12 with return value + 1;
Show answer and explanation

Answer: C

The method parameter is named value, which shadows the instance variable value. The statement value = value + 1 modifies the local parameter, not the instance variable. The instance variable remains 0. The fix is to use this.value to refer to the instance variable explicitly. Writing this.value = this.value + 1 ensures the instance variable is incremented. While renaming the parameter would also work, shadowing is the root cause of the error, and using the this keyword is the direct fix.

Question 15

Consider the following classes.

public class Point
{
  private int x;
  private int y;

  public Point(int x, int y)
  {
    this.x = x;
    this.y = y;
  }

  public int getX() { return x; }
  public int getY() { return y; }
}
public class Segment{
  private Point start;
  private Point end;

  public Segment(Point p1, Point p2)
  {
    start = p1;
    end = p2;
  }

  public Point getMidpoint()
  {
    int mx = (start.getX() + end.getX()) / 2;
    int my = (start.getY() + end.getY()) / 2;
    return new Point(mx, my);
  }
}
Point a = new Point(2, 8);
Point b = new Point(10, 4);
Segment seg = new Segment(a, b);
Point mid = seg.getMidpoint();
System.out.println(mid.getX() + " " + mid.getY());
What is printed as a result of executing this code segment?
  • A5 5
  • B6 6
  • C6 4
  • D12 12
Show answer and explanation

Answer: B

The getMidpoint method computes the midpoint of the two endpoints. The x-coordinate of the midpoint is (2 + 10) / 2 = 12 / 2 = 6 (integer division). The y-coordinate is (8 + 4) / 2 = 12 / 2 = 6. A new Point(6, 6) is returned. Calling getX() and getY() on this point returns 6 and 6. The output is 6 6. This traces a method that creates and returns a new object using data from the calling object.

Question 16

The following method is intended to transpose a square 2D array (swap rows and columns) so that the element at [r][c] moves to [c][r].

public static void transpose(int[][] mat)
{
  int n = mat.length;
  for (int r = 0; r < n; r++)
  {
    for (int c = /* missing code */; c < n; c++)
    {
      int temp = mat[r][c];
      mat[r][c] = mat[c][r];
      mat[c][r] = temp;
    }
  }
}
Which of the following can replace /* missing code */ so that the method works as intended?
  • A0
  • B1
  • Cr + 1
  • Dn - r
Show answer and explanation

Answer: C

To transpose a matrix in-place, each pair of elements [r][c] and [c][r] should be swapped exactly once. If the inner loop starts at c = 0, every pair is swapped twice (once when processing [r][c] and again when processing [c][r]), resulting in no change. Starting c at r + 1 ensures that only the upper triangle is processed, and each pair is swapped exactly once. Starting at c = 1 for every row misses swaps in the first column for rows after row 0. Starting at n - r processes different regions for each row and results in some pairs being swapped twice (undone) while others are missed entirely.

Ready for the full-length tests?

Five full-length AP Computer Science A practice tests, every unit of notes and step-by-step solutions. 7 days free.

Start my free 7 days →