Practice Test 1 - AP Computer Science A

20 questions. Answer them in any order, then submit to see your score and every explanation.

  1. Based on the provided 2D array, for int[][] nums = {{-2,4},{6,1},{0,-3}}, what is the output of a method that returns the sum of all elements?
  2. A software developer is creating an application for a local library to manage its book collection. Which of the following best exemplifies a data set the developer would need to use for this application?
  3. Considering the class design, a game studio is building a 2D adventure game where players explore levels and fight enemies. The design centers on three classes: GameCharacter, Player, and Enemy. GameCharacter is a superclass that stores private health and position fields and provides methods like takeDamage(amount), move(dx, dy), and isAlive(). Player and Enemy inherit from GameCharacter. Player adds an inventory and a method useItem(item), while Enemy adds an aiType and a method chooseAction(). The team also created an abstract class Attack with an abstract method apply(GameCharacter target). Specific attacks like MeleeAttack and FireballAttack extend Attack and implement apply differently. During combat, CombatSystem stores a list of Attack objects and calls apply on each one without checking its exact type. This keeps combat code short and readable, because CombatSystem does not need separate if-statements for every attack. When designers add a new attack later, they only create a new subclass of Attack; they do not change CombatSystem. The team notes that good class design also helps performance by avoiding repeated code paths and reducing unnecessary checks. Based on the scenario, how does polymorphism in the described classes benefit the program?
  4. Refer to the Student class code below: what value will the field id have after executing new Student("Ana")? public class Student { private String name; private int id; // Public constructor: sets name only, defaults id to 0. public Student(String name) { this(name, 0); // Constructor chaining to reuse full initialization } // Public parameterized constructor: sets both name and id. public Student(String name, int id) { this.name = name; this.id = id; } // Private default constructor: prevents creating a nameless student. private Student() { this("Unknown", 0); } }
  5. In this game inventory, what is the value of item after set and get?import java.util.ArrayList; public class GameDemo { public static void main(String[] args) { ArrayList<String> inventory = new ArrayList<String>(); inventory.add("Potion"); inventory.add("Sword"); inventory.add("Shield"); inventory.set(0, "Elixir"); String item = inventory.get(0); System.out.println(item); } }
  6. Analyze the following code.// Conditional loop: stop when target is found int[] data = {2, 4, 6, 8, 10}; // sequence int i = 0; // initialization int target = 8; while (i < data.length && data[i] != target) { // condition i++; // update } System.out.println(i);What will be the output of the given code?
  7. Based on the scenario, what is the value stored at board[0][2] after X moves there on a tic-tac-toe board?
  8. What is the purpose of the loop in the provided code? // Part A: Setup ArrayList<Double> prices = new ArrayList<>(); prices.add(2.5); prices.add(null); prices.add(1.0); // Part B: Sum values safely double totalSum = 0.0; for (Double price : prices) { // traverse list if (price != null) { totalSum += price; // add non-null values } } // Part C: Output System.out.println(totalSum);
  9. Problem: Count character frequencies. Input: inputString (length 0–1000) containing only lowercase letters a–z. Output: an int[] counts of length 26 where counts[0] is the number of 'a's, counts[25] is the number of 'z's. No external libraries. Function signature: public static int[] countLetters(String inputString). Given the problem description above, which statement correctly updates counts for character ch?
  10. In the StudentRecord code below, what information do the inline comments provide in this program? import java.util.ArrayList; import java.util.List; /** * Maintains quiz scores and computes an average. * Demonstrates how inline comments can justify small design choices. */ public class StudentRecord { private final List<Integer> quizScores = new ArrayList<>(); /** * Adds a quiz score from 0 to 10. * * @param score the quiz score * @return true if the score is stored */ public boolean addQuizScore(int score) { if (score < 0 || score > 10) { // Enforce the stated scale so the average remains interpretable. return false; } quizScores.add(score); return true; } /** * Computes the arithmetic mean of stored quiz scores. * * @return the average, or 0.0 if no scores exist */ public double averageScore() { if (quizScores.isEmpty()) { // Avoid dividing by zero when no scores have been added. return 0.0; } int sum = 0; for (int score : quizScores) { // Accumulate the total to compute the mean in one pass. sum += score; } return (double) sum / quizScores.size(); } }
  11. A developer is testing a program by running it with various inputs and checking if the outputs are correct. What type of error is this process primarily designed to uncover?
  12. Refer to the code below. What is the output of the loop if the input array is [1, 2, 3, 4]? public class EvenSumExample { public static void main(String[] args) { // Input array to iterate over int[] numbers = {1, 2, 3, 4}; // Accumulator for the sum of even numbers int evenSum = 0; // For loop: initialize index, test condition, then increment index for (int index = 0; index < numbers.length; index++) { // Selection: only add even values if (numbers[index] % 2 == 0) { evenSum += numbers[index]; } } // Output the computed sum System.out.println("Even sum: " + evenSum); } }
  13. Which of the following real-world scenarios is best modeled using only sequencing, without selection or repetition?
  14. Given the task requirements, what will be the output after executing the provided code snippet? You are implementing selection sort. After each outer-loop pass, the smallest remaining element is swapped into position i. Use iteration for scanning and selection for tracking the minimum. Input: nn, then nn integers. Output: sorted array. Constraints: 1≤n≤1001 \le n \le 100; values in [-1000,1000]. Example input: 4 5 2 9 1 Example output: 1 2 5 9 Code snippet:int[] a = {5, 2, 9, 1}; **for** (int i = 0; i < a.length - 1; i++) { int min = i; **for** (int j = i + 1; j < a.length; j++) { **if** (a[j] < a[min]) { min = j; } } int tmp = a[i]; a[i] = a[min]; a[min] = tmp; } System.out.print(a[0] + " " + a[1]);
  15. Consider the following code segment: Counter c1 = new Counter(); Counter c2 = new Counter(10); c1.increment(); c1.increment(5); c2.increment(); c2.reset(); c2.increment(3); What will be printed by System.out.println(c1.getValue() + " " + c2.getValue());?
  16. Given the task requirements, which of the following correctly implements the required loop structure? Problem description (Search Algorithm) A Java program performs linear search on an int[] arr to find target. It must scan from left to right using iteration and use selection to stop early when the target is found. If found, print Found at index k; otherwise print Not found. Input - Line 1: integer n - Line 2: n integers - Line 3: target Output - Found at index k or Not found Constraints - 1≤n≤2001 \le n \le 200 - Values are integers in [−1000,1000][-1000, 1000] Choose the correct loop header/body pattern to scan all indices unless the target is found (assume foundIndex starts at -1).
  17. Consider the following class and main method; how do you create an instance of BankAccount? public class BankAccount { private String owner; private double balance; // Constructor sets up a new account with an initial balance. public BankAccount(String owner, double initialBalance) { this.owner = owner; balance = initialBalance; } // deposit adds money to the account. public void deposit(double amount) { balance += amount; } public static void main(String[] args) { // The account object is created and then manipulated. // Example method invocation on an instantiated object: // acct.deposit(50.0); } }
  18. A student writes a program to calculate 10 / x, where x is an integer input by the user. The program compiles successfully. When the program is run and the user enters 2, it works correctly. When the user enters 0, the program terminates with an ArithmeticException. This exception is an example of what type of error?
  19. A BankAccount class has methods void deposit(double amount) and boolean withdraw(double amount). If BankAccount acct = new BankAccount(40.0); what is returned when withdraw(60.0) is called, assuming it fails when funds are insufficient?
  20. What problem does this solve in the provided Rectangle class definition? class Rectangle { private int length; private int width; public Rectangle(int length, int width) { this.length = length; this.width = width; this.printArea(); } public void printArea() { System.out.println(this.length * this.width); } }

Practice tests