Practice Test 6 - AP Computer Science A
20 questions. Answer them in any order, then submit to see your score and every explanation.
- Considering the Java class example below, how does inheritance benefit the class structure illustrated?
public class Animal { public void eat() { System.out.println("Eating"); } } public class Dog extends Animal { public void fetch() { System.out.println("Fetching"); } } // Encapsulation: fields would be private (not shown). // Inheritance: Dog gets eat() without rewriting it. // Polymorphism: overridden methods can vary (not shown).Based on the class structure presented above, how does inheritance help Dog? - A retailer's Inventory Management System must handle frequent restocks and customer orders while preventing stock from going negative. The team creates Product, Inventory, and Order. Product has private fields productId, name, and quantity, and it provides addStock and removeStock methods that validate inputs. Inventory stores Product objects and offers restock and reserve methods that call Product's methods, keeping all quantity rules inside Product. Order contains line items and processes by asking Inventory to reserve each item; if any reserve fails, the order is not completed. Later, the team adds DigitalProduct extends Product, overriding removeStock so quantity never decreases, because digital items have unlimited supply. Order and Inventory still treat items as Product, so they don't need edits. This improves maintainability because new product types are added by extending Product and overriding behavior, not by rewriting order processing. Readability improves because rules are located in the class responsible for them. Performance stays reasonable because validation happens once per stock change rather than scattered checks across multiple classes. Considering the class design, what role does inheritance play in the class design described?
- Palindrome Checker: What is the result of the following code snippet when the input is "RaceCar"?
String word = input.toUpperCase(); String first = word.substring(0, 1); String last = word.substring(word.length() - 1); System.out.println(first + last); - In the code snippet below, what problem does 'this' solve in the provided class definition?
class Rectangle { private int length; private int width; public Rectangle(int length, int width) { // 'this' distinguishes instance variables from parameters this.length = length; this.width = width; } public int area() { // method call on the current object return this.computeArea(); } private int computeArea() { return length * width; } } - In this inventory system, what is the output after using set and then get?
import java.util.ArrayList; public class InventoryDemo { public static void main(String[] args) { ArrayList<Integer> qty = new ArrayList<Integer>(); // quantities per item qty.add(5); qty.add(2); qty.add(9); qty.set(1, 7); // update second item's quantity System.out.println(qty.get(1)); // print updated quantity } } - What will be the output of the given code snippet?
// Part A: Setup ArrayList<Integer> numbers = new ArrayList<>(); // Part B: Find maximum int maxValue = Integer.MIN_VALUE; for (int value : numbers) { // traverse list if (value > maxValue) { maxValue = value; } } // Part C: Handle empty list if (numbers.size() == 0) { System.out.println("empty"); } else { System.out.println(maxValue); } - In this recursive merge sort, how does the recursive call structure ensure the entire array becomes sorted?
public class Sorter { public static void mergeSort(int[] nums, int left, int right) { if (left >= right) { return; } int mid = (left + right) / 2; // Recursive calls sort subarrays mergeSort(nums, left, mid); mergeSort(nums, mid + 1, right); // Merge combines two sorted subarrays merge(nums, left, mid, right); } private static void merge(int[] nums, int left, int mid, int right) { int[] temp = new int[right - left + 1]; int i = left, j = mid + 1, k = 0; while (i <= mid && j <= right) { temp[k++] = (nums[i] <= nums[j]) ? nums[i++] : nums[j++]; } while (i <= mid) temp[k++] = nums[i++]; while (j <= right) temp[k++] = nums[j++]; for (int t = 0; t < temp.length; t++) nums[left + t] = temp[t]; } } - A school stores grades in an int[] gradeList; the algorithm iterates to compute average and count grades >= threshold. Inputs are gradeList and threshold; outputs are average and countAbove. Example input: [80, 90, 70], threshold 85; output: average 80.0, countAbove 1. Example input: [100, 60], threshold 70; output: average 80.0, countAbove 1.
// Compute average and count grades at or above threshold int sum = 0; int countAbove = 0; for (int i = 0; i < gradeList.length; i++) { sum += gradeList[i]; if (gradeList[i] >= threshold) { countAbove++; } } double average = (double) sum / gradeList.length; System.out.println(average + "," + countAbove);Consider the algorithm for processing grades; which part ensures every grade is compared to threshold exactly once? - A data set contains the names and final grades for all students in a course. A program is written that goes through this data set and changes every student's final grade to 100. Which of the following best describes the program's operation on the data set?
- Consider a class named
Playlistdesigned to represent a collection of songs. Which of the following is an example of an attribute that would be defined within thePlaylistclass? - Consider an algorithm for withdrawing money from an ATM: 1. Insert card. 2. Enter PIN. 3. If PIN is correct, display transaction options. 4. Select withdrawal amount. 5. If account balance is sufficient, dispense cash. 6. Eject card. The step "If account balance is sufficient, dispense cash" is an example of what?
- Identify the function of the Javadoc comments in this BankAccount class and its documented methods.
- In this game inventory, what is the output after remove and then get?
import java.util.ArrayList; public class GameDemo { public static void main(String[] args) { ArrayList<String> items = new ArrayList<String>(); items.add("Potion"); items.add("Key"); items.add("Map"); items.remove(0); // use potion System.out.println(items.get(0)); // new first item } } - A store tracks weekly sales in an int[] and uses totals for restocking decisions. Consider:
A farmer's market vendor records daily smoothie sales in an int[] for a 7-day festival to decide how much fruit to bring the next morning. The vendor wants to quickly compute the total sales for the week and the average per day, using a simple loop over the array. Since the data set size is fixed, the array avoids resizing overhead.
int[] dailySales = {5, 7, 6, 9, 8, 10, 4}; int total = 0; for (int i = 0; i < dailySales.length; i++) { total = dailySales[i]; // update total } System.out.println(total);Refer to the problem scenario in the passage, identify the error in the following code snippet and suggest a fix. - Which code snippet correctly demonstrates iterative factorial using a for loop and an accumulator variable in Java?
- How many recursive calls are made by
isPal("abba")before reaching the base case?boolean isPal(String s) { if (s.length() <= 1) return true; if (s.charAt(0) != s.charAt(s.length()-1)) return false; return isPal(s.substring(1, s.length()-1)); } ``` - For the recursive binary search method below, what is the time complexity of the given recursive algorithm?
public class Searcher { public static int binarySearch(int[] nums, int target, int low, int high) { if (low > high) { return -1; } int mid = (low + high) / 2; if (nums[mid] == target) { return mid; } if (target < nums[mid]) { return binarySearch(nums, target, low, mid - 1); } else { return binarySearch(nums, target, mid + 1, high); } } } - A program searches an unsorted list of usernames to find a target name.
public static int findUser(String[] users, String target) { for (int i = 0; i < users.length; i++) { if (users[i].equals(target)) { return i; } } return -1; }How does the run-time of this algorithm change as the input size doubles? - Which of the following is an invalid variable name in Java?
- Based on the temperature conversion tool below, how does changing fahrenheit from double to int affect the printed output?
double celsius = 37.0; Converter conv = new Converter(); double fahrenheit = conv.toFahrenheit(celsius); System.out.println(fahrenheit);