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.
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 methodgetNextValue(), which returns-1when there is no more data.</>Javapublic 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.
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
totalRatingsinputs using a helper methodgetRating().</>Javapublic 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.
Question 3
The method
longestHeatWaveprocesses a data set of temperatures to find the maximum number of consecutive days where the temperature exceeded 90 degrees. The methodgetTemp()returns the next daily temperature, returning-999when there is no more data.</>Javapublic 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.
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, andgetNext()returns the next transaction amount.</>Javapublic 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.
Question 5
The following method is intended to find the index of the last occurrence of
targetinlist. Iftargetis not found, the method should return-1.</>Javapublic 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
lastIndexwithout 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
valappears in the 2D arraymat.</>Javapublic 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.Question 7
The
hasNegativemethod is intended to returntrueif the arrayarrcontains at least one negative number, andfalseotherwise. The method does not work as intended.</>Javapublic 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
elseblock and its return statement entirely.Change the
return false;inside the loop toreturn true;.Change the condition in the
ifstatement toarr[i] <= 0.Swap the
return true;andreturn 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
elseblock allows the loop to continue checking subsequent elements if the current element is not negative.Question 8
The
Studentclass contains agetNamemethod that returns a student's name as aString. The following method is intended to find the index of the first student inrosterwhose name matchestargetName.</>Javapublic 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 indexiproperly indicates the position of the first match.Question 9
The following method is intended to concatenate all the strings in the array
lettersand return the resulting string.</>Javapublic 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
wordbefore 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?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
lowesttotemps[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.
- FRQ 3 – Data Analysis with ArrayList (26 questions)
- FRQ 4 – 2D Array (25 questions)
Review Unit 4 before you start
- 4.1 Ethical and Social Implications
- 4.2 Introduction to Using Data Sets
- 4.3 Array Creation and Access
- 4.4 Traversing Arrays
- 4.5 Developing Algorithms Using Arrays
- 4.6 Using Text Files
- 4.7 Wrapper Classes: Integer and Double
- 4.8 ArrayList Methods
- 4.9 Traversing ArrayLists
- 4.10 Developing Algorithms Using ArrayLists
- 4.11 2D Arrays
- 4.12 Traversing 2D Arrays
- 4.13 Implementing 2D Array Algorithms
- 4.14 Searching
- 4.15 Sorting
- 4.16 Recursion
- 4.17 Recursive Searching and Sorting