---
title: "AP Computer Science A Unit 4 Practice Test"
description: "A timed AP Computer Science A Unit 4 (Data Collections) practice test in the AP format, drawn from 1,810 multiple-choice questions and 51 FRQs written for the unit. The standard version takes about 88 minutes."
canonical: "https://fiveable.me/ap-comp-sci-a/unit-test/4"
type: "unit-test"
subject: "AP Computer Science A"
unit: "Unit 4"
---

# AP Computer Science A Unit 4 Practice Test

## Overview

A timed AP Computer Science A Unit 4 (Data Collections) practice test in the AP format, drawn from 1,810 multiple-choice questions and 51 FRQs written for the unit. The standard version takes about 88 minutes.

## Test Format

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

## Unit FRQs by Type

- [FRQ 3 – Data Analysis with ArrayList](/ap-comp-sci-a/frqs/arraylist?unit=4): 26 questions
- [FRQ 4 – 2D Array](/ap-comp-sci-a/frqs/2d-array?unit=4): 25 questions

## Practice Questions

### 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?

- (A) `if (val > target) { count++; } val = getNextValue();`
- (B) `if (val > target) { count++; val = getNextValue(); }`
- (C) `val = getNextValue(); if (val > target) { count++; }`
- (D) `if (val < target) { count++; } val = getNextValue();`

**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.

### 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?

- (A) `if (score > 0) { sum += score; count++; }`
- (B) `if (score > 0) { sum += score; } count++;`
- (C) `if (score > 0) { count += score; sum++; }`
- (D) `if (score < 0) { sum += score; count++; }`

**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.

### 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?

- (A) `if (temp > 90) { curCount++; } else { curCount = 0; } if (curCount > maxCount) { maxCount = curCount; }`
- (B) `if (temp > 90) { curCount++; } if (curCount > maxCount) { maxCount = curCount; } else { curCount = 0; }`
- (C) `if (temp > 90) { maxCount++; } else { maxCount = 0; } if (maxCount > curCount) { curCount = maxCount; }`
- (D) `if (temp > 90) { curCount++; } else { curCount = 0; } if (maxCount > curCount) { curCount = maxCount; }`

**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.

### 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?

- (A) `if (amount > 500) { amount = 500; } total += amount;`
- (B) `if (amount > 500) { total += 500; } total += amount;`
- (C) `if (total > 500) { amount = 500; } total += amount;`
- (D) `if (amount < 500) { amount = 500; } total += amount;`

**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.

### 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?

- (A) `if (list.get(i).equals(target)) { lastIndex = i; }`
- (B) `if (list.get(i).equals(target)) { return i; }`
- (C) `if (list.get(i) == target) { lastIndex = i; }`
- (D) `if (list.get(i) == target) { return i; }`

**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.

### 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?

- (A) `for (int i = 0; i < row.length; i++) { if (row[i] == val) count++; }`
- (B) `for (int i = 0; i < mat.length; i++) { if (row[i] == val) count++; }`
- (C) `for (int i = 0; i < row.length; i++) { if (row[i] != val) count++; }`
- (D) `for (int i = 1; i < row.length; i++) { if (row[i] == val) count++; }`

**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.

### 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?

- (A) Remove the `else` block and its return statement entirely.
- (B) Change the `return false;` inside the loop to `return true;`.
- (C) Change the condition in the `if` statement to `arr[i] <= 0`.
- (D) Swap the `return true;` and `return false;` statements inside.

**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.

### 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?

- (A) `if (roster[i].getName().equals(targetName)) return i;`
- (B) `if (roster[i].getName().equals(targetName)) return -1;`
- (C) `if (roster[i].getName() == targetName) return i;`
- (D) `if (roster[i].equals(targetName)) return i;`

**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.

### 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?

- (A) `String word = ""; for(String s : letters) { word += s; }`
- (B) `for(String s : letters) { String word = ""; word += s; }`
- (C) `String word = ""; for(String s : letters) { s += word; }`
- (D) `for(String s : letters) { String word = s; word += s; }`

**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.

### 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?

- (A) Changing line 3 to: int lowest = temps[0];
- (B) Changing line 3 to: int lowest = temps[1];
- (C) Changing line 5 to: if (t >= lowest)
- (D) Changing line 6 to: temps[0] = lowest;

**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.

## Review the Unit

- [4.1 Ethical and Social Implications](/ap-comp-sci-a/unit-4/ethical-and-social-implications/study-guide/iec7yzDQ2qENx5UAdiPJ)
- [4.2 Introduction to Using Data Sets](/ap-comp-sci-a/unit-4/introduction-to-using-data-sets/study-guide/fq4I4p0XINBBV56xQfTx)
- [4.3 Array Creation and Access](/ap-comp-sci-a/unit-4/array-creation-and-access/study-guide/umTe6NA38OqZOhMZjFWi)
- [4.4 Traversing Arrays](/ap-comp-sci-a/unit-4/traversing-arrays/study-guide/kRcOqfawCcBz6gcT646t)
- [4.5 Developing Algorithms Using Arrays](/ap-comp-sci-a/unit-4/developing-algorithms-using-arrays/study-guide/c6dpJfmjG7oVFDqnXFAk)
- [4.6 Using Text Files](/ap-comp-sci-a/unit-4/using-text-files/study-guide/JhiQXb5r4daUivzP1Xkm)
- [4.7 Wrapper Classes: Integer and Double](/ap-comp-sci-a/unit-4/wrapper-classes-integer-double/study-guide/CKbVZpoW1SH2jmwauzDE)
- [4.8 ArrayList Methods](/ap-comp-sci-a/unit-4/arraylist-methods/study-guide/8juIkbLwLGELYtblBeCf)
- [4.9 Traversing ArrayLists](/ap-comp-sci-a/unit-4/traversing-arraylists/study-guide/U4SdcheNw5PMSIzjU2oL)
- [4.10 Developing Algorithms Using ArrayLists](/ap-comp-sci-a/unit-4/developing-algorithms-using-arraylists/study-guide/MKbteieYvLOpWIwfqiND)
- [4.11 2D Arrays](/ap-comp-sci-a/unit-4/2d-arrays/study-guide/5WDx6ZFeWhx2aVuiZI6R)
- [4.12 Traversing 2D Arrays](/ap-comp-sci-a/unit-4/traversing-2d-arrays/study-guide/ZBcYqrg8FMJ49z1XpR8f)
- [4.13 Implementing 2D Array Algorithms](/ap-comp-sci-a/unit-4/implementing-2d-array-algorithms/study-guide/9ucC5cB6ffrLnA4b3FU3)
- [4.14 Searching](/ap-comp-sci-a/unit-4/searching/study-guide/8PTb7wMUSzHeI7aTUFNy)
- [4.15 Sorting](/ap-comp-sci-a/unit-4/sorting/study-guide/P5PACxSTKavEy6V3x3Nt)
- [4.16 Recursion](/ap-comp-sci-a/unit-4/recursion/study-guide/p4D3YegZCLwQ3KJVvsd4)
- [4.17 Recursive Searching and Sorting](/ap-comp-sci-a/unit-4/recursive-searching-and-sorting/study-guide/tP6n1uldmjMrgteAVspr)

## Other Unit Tests

- [Unit 1: Using Objects and Methods](/ap-comp-sci-a/unit-test/1)
- [Unit 2: Selection and Iteration](/ap-comp-sci-a/unit-test/2)
- [Unit 3: Class Creation](/ap-comp-sci-a/unit-test/3)

## About This Document

Canonical Fiveable pages are available as Markdown at the same path plus `.md`.

- [llms.txt](https://fiveable.me/llms.txt): index of Fiveable's sections and URL patterns
- [llms-full.txt](https://fiveable.me/llms-full.txt): complete subject and unit listing
- [MCP server](https://fiveable.me/mcp): call Fiveable as tools instead of fetching pages (`https://fiveable.me/api/mcp`)
- [MCP server for AP teachers](https://fiveable.me/mcp/teachers): a teacher's classes, assignments and AP-rubric grading (`https://fiveable.me/api/mcp/teacher`)
