Skip to main content

AP Computer Science A Unit 4 practice questions

Try 10 multiple-choice questions from Unit 4 here. Pick an answer to see why it's right or wrong, then take the timed test above for a full AP-style set.

  1. Question 1

    A method processes a data set of positive integers to count how many values exceed a specific target. The values are provided by a helper method getNextValue(), which returns -1 when there is no more data.

    </>Java
    public int countAboveTarget(int target) {
        int count = 0;
        int val = getNextValue();
        while (val != -1) {
            /* missing code */
        }
        return count;
    }

    Which of the following code segments can replace /* missing code */ so that the method works as intended?

    if (val > target) { count++; } val = getNextValue();

    if (val > target) { count++; val = getNextValue(); }

    val = getNextValue(); if (val > target) { count++; }

    if (val < target) { count++; } val = getNextValue();

    Show answer

    Answer: (A)

    Correctly checks the condition and updates the loop variable outside the if-statement. This ensures the sequence continues processing regardless of whether the current value exceeds the target.

  2. Question 2

    A method is intended to calculate the average customer rating from a data set, but it should only include positive ratings (ratings greater than 0) in its calculation. The method processes exactly totalRatings inputs using a helper method getRating().

    </>Java
    public double getPositiveAverage(int totalRatings) {
        int sum = 0;
        int count = 0;
        for (int i = 0; i < totalRatings; i++) {
            int score = getRating();
            /* missing code */
        }
        if (count == 0) { return 0.0; }
        return (double) sum / count;
    }

    Which of the following code segments can replace /* missing code */ so that the method works as intended?

    if (score > 0) { sum += score; count++; }

    if (score > 0) { sum += score; } count++;

    if (score > 0) { count += score; sum++; }

    if (score < 0) { sum += score; count++; }

    Show answer

    Answer: (A)

    Correctly accumulates both the sum of the valid scores and the count of valid scores inside the conditional block. This ensures the average is calculated using only the positive ratings.

  3. Question 3

    The method longestHeatWave processes a data set of temperatures to find the maximum number of consecutive days where the temperature exceeded 90 degrees. The method getTemp() returns the next daily temperature, returning -999 when there is no more data.

    </>Java
    public int longestHeatWave() {
        int maxCount = 0;
        int curCount = 0;
        int temp = getTemp();
        while (temp != -999) {
            /* missing code */
            temp = getTemp();
        }
        return maxCount;
    }

    Which of the following code segments can replace /* missing code */ so that the method works as intended?

    if (temp > 90) { curCount++; } else { curCount = 0; } if (curCount > maxCount) { maxCount = curCount; }

    if (temp > 90) { curCount++; } if (curCount > maxCount) { maxCount = curCount; } else { curCount = 0; }

    if (temp > 90) { maxCount++; } else { maxCount = 0; } if (maxCount > curCount) { curCount = maxCount; }

    if (temp > 90) { curCount++; } else { curCount = 0; } if (maxCount > curCount) { curCount = maxCount; }

    Show answer

    Answer: (A)

    Correctly increments the current streak if the condition is met and resets it to zero if not. It then independently checks if the current streak has surpassed the maximum streak, ensuring accurate tracking.

  4. Question 4

    A method processes a data set of daily transaction amounts to calculate total revenue. Any single transaction greater than 500 is capped at exactly 500 before being added to the total. The method hasMore() returns true if there are more transactions, and getNext() returns the next transaction amount.

    </>Java
    public int getCappedTotal() {
        int total = 0;
        while (hasMore()) {
            int amount = getNext();
            /* missing code */
        }
        return total;
    }

    Which of the following code segments can replace /* missing code */ so that the method works as intended?

    if (amount > 500) { amount = 500; } total += amount;

    if (amount > 500) { total += 500; } total += amount;

    if (total > 500) { amount = 500; } total += amount;

    if (amount < 500) { amount = 500; } total += amount;

    Show answer

    Answer: (A)

    Correctly checks the current data value and caps it at 500 if it exceeds the limit. It then adds the processed value to the running total, ensuring no transaction contributes more than the maximum allowed.

  5. Question 5

    The following method is intended to find the index of the last occurrence of target in list. If target is not found, the method should return -1.

    </>Java
    public static int findLast(ArrayList<String> list, String target) {
        int lastIndex = -1;
        for (int i = 0; i < list.size(); i++) {
            /* missing code */
        }
        return lastIndex;
    }

    Which of the following code segments can replace /* missing code */ so that the method works as intended?

    if (list.get(i).equals(target)) { lastIndex = i; }

    if (list.get(i).equals(target)) { return i; }

    if (list.get(i) == target) { lastIndex = i; }

    if (list.get(i) == target) { return i; }

    Show answer

    Answer: (A)

    Implementing a search for the last occurrence requires updating a variable each time a match is found and allowing the loop to finish. By continuously updating lastIndex without returning early, the method correctly stores the index of the final match.

  6. Question 6

    The following method is intended to count the number of times val appears in the 2D array mat.

    </>Java
    public static int countVal(int[][] mat, int val) {
        int count = 0;
        for (int[] row : mat) {
            /* missing code */
        }
        return count;
    }

    Which of the following code segments can replace /* missing code */ so that the method works as intended?

    for (int i = 0; i < row.length; i++) { if (row[i] == val) count++; }

    for (int i = 0; i < mat.length; i++) { if (row[i] == val) count++; }

    for (int i = 0; i < row.length; i++) { if (row[i] != val) count++; }

    for (int i = 1; i < row.length; i++) { if (row[i] == val) count++; }

    Show answer

    Answer: (A)

    Traversing a 2D array requires accessing each 1D array (row) and then iterating through its elements. This inner loop correctly iterates from 0 to row.length, checking each element against the target value.

  7. Question 7

    The hasNegative method is intended to return true if the array arr contains at least one negative number, and false otherwise. The method does not work as intended.

    </>Java
    public static boolean hasNegative(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] < 0) {
                return true;
            } else {
                return false;
            }
        }
        return false;
    }

    Which of the following changes makes the method work as intended?

    Remove the else block and its return statement entirely.

    Change the return false; inside the loop to return true;.

    Change the condition in the if statement to arr[i] <= 0.

    Swap the return true; and return false; statements inside.

    Show answer

    Answer: (A)

    Recognizing that a linear search for existence should only return early when the target is found. Removing the else block allows the loop to continue checking subsequent elements if the current element is not negative.

  8. Question 8

    The Student class contains a getName method that returns a student's name as a String. The following method is intended to find the index of the first student in roster whose name matches targetName.

    </>Java
    public static int findStudent(Student[] roster, String targetName) {
        for (int i = 0; i < roster.length; i++) {
            /* missing code */
        }
        return -1;
    }

    Which of the following code segments can replace /* missing code */ so that the method works as intended?

    if (roster[i].getName().equals(targetName)) return i;

    if (roster[i].getName().equals(targetName)) return -1;

    if (roster[i].getName() == targetName) return i;

    if (roster[i].equals(targetName)) return i;

    Show answer

    Answer: (A)

    Accessing the object's property using the getter method and comparing it with .equals() correctly checks for string content equality. Returning the loop index i properly indicates the position of the first match.

  9. Question 9

    The following method is intended to concatenate all the strings in the array letters and return the resulting string.

    </>Java
    public static String buildWord(String[] letters) {
        /* missing code */
        return word;
    }

    Which of the following code segments can replace /* missing code */ so that the method works as intended?

    String word = ""; for(String s : letters) { word += s; }

    for(String s : letters) { String word = ""; word += s; }

    String word = ""; for(String s : letters) { s += word; }

    for(String s : letters) { String word = s; word += s; }

    Show answer

    Answer: (A)

    Identifying that a variable must be declared in a scope that encompasses all its uses. Declaring word before the loop ensures it is accessible both inside the loop for concatenation and outside the loop for the return statement.

  10. Question 10

    Consider the following method, which is intended to find and return the lowest temperature recorded in a data set of daily temperatures.

    </>Java
    /** Precondition: temps contains at least one element. */
    public int findLowestTemp(int[] temps) {
        int lowest = 0; // line 3
        for (int t : temps) {
            if (t < lowest) { // line 5
                lowest = t; // line 6
            }
        }
        return lowest;
    }

    This method does not always work as intended. For example, if all temperatures in the data set are positive, it will incorrectly return 0. Which of the following changes can be made so that the code segment works as intended?

    Changing line 3 to: int lowest = temps[0];

    Changing line 3 to: int lowest = temps[1];

    Changing line 5 to: if (t >= lowest)

    Changing line 6 to: temps[0] = lowest;

    Show answer

    Answer: (A)

    Identifying that the minimum value tracker must be initialized to a valid element from the data set. By setting lowest to temps[0], the algorithm correctly compares subsequent temperatures against an actual recorded value rather than an arbitrary baseline of 0.

What's on the AP Computer Science A Unit 4 practice test

The standard version takes about 88 minutes and follows the timing and directions of the AP exam, sized to one unit:

  • 20 Multiple Choice Questions (43 minutes)
  • 1 FRQ – FRQ 3 – Data Analysis with ArrayList (23 minutes)
  • 1 FRQ – FRQ 4 – 2D Array (23 minutes)

Questions are drawn from 1810 multiple-choice questions and 51 FRQs written for Unit 4, Data Collections.

Practice AP Computer Science A Unit 4 FRQs

Answer the unit's free-response questions one at a time and get a score on every part.

Review Unit 4 before you start

Other AP Computer Science A unit tests