Practice Test 2 - AP Computer Science A

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

  1. What would happen if the class variable were not static? // BankAccount tracks bank-wide total funds using a static class variable. public class BankAccount { // Class variable shared by all accounts. private static double bankTotalBalance = 0.0; // Instance variable per account. private double accountBalance; // Constructor updates both instance and shared totals. public BankAccount(double openingDeposit) { accountBalance = openingDeposit; bankTotalBalance += openingDeposit; } // Static method reads the shared total. public static double getBankTotalBalance() { return bankTotalBalance; } // Main method demonstrates shared total. public static void main(String[] args) { BankAccount a = new BankAccount(40.0); BankAccount b = new BankAccount(60.0); System.out.println(BankAccount.getBankTotalBalance()); } }
  2. A student counts how many pairs of different values appear in an int[] of size nn.public static int countDifferentPairs(int[] data) { int count = 0; for (int i = 0; i < data.length; i++) { for (int j = i + 1; j < data.length; j++) { if (data[i] != data[j]) { count++; } } } return count; }What is the run-time complexity of the algorithm in the code snippet?
  3. Consider the Student class shown above. After the following sequence of operations, what will be the values returned by s2.getId() and Student.getNextId(), respectively? Student s1 = new Student("Alice"); Student s2 = new Student("Bob"); Student s3 = new Student("Carol"); Student.resetIdCounter(); Student s4 = new Student("David");
  4. The recursive method above is called on a sorted array of 7 elements with search(arr, target, 0, 6) where the target is NOT in the array. What is the time complexity of this search method?
  5. Based on the code snippet above, what is returned by the method deposit? Describe its significance. public class BankAccount { private String accountNumber; private double balance; public BankAccount(String accountNumber, double balance) { this.accountNumber = accountNumber; this.balance = balance; } // Adds funds to this account public void deposit(double amount) { balance += amount; } // Deposits then returns this same account reference public BankAccount depositAndReturn(double amount) { deposit(amount); return this; } public double getBalance() { return balance; } public static void main(String[] args) { BankAccount acct = new BankAccount("A100", 50.0); BankAccount ref = acct.depositAndReturn(25.0); System.out.println(acct.getBalance()); System.out.println(ref.getBalance()); } }
  6. A method rotates a square 2D array 90 degrees clockwise. After the rotation, element at position (i, j) in the original array should be at position (j, n-1-i) where n is the array dimension. What is the correct approach to implement this in-place rotation?
  7. Password Validator: What will be the output if the string is "Abc1-Def"? String password = input; password = password.replace("-", ""); boolean longEnough = password.length() >= 8; boolean hasDigit = password.indexOf("1") >= 0; System.out.println(longEnough && hasDigit);
  8. An ArrayList wordList contains ["the", "quick", "brown", "fox", "jumps"]. What are the contents of the ArrayList returned by the call ListFilter.filterByLength(wordList, 5)?
  9. A game casts a large double into an int score: class ScoreTracker { public static int unsafeCast(double totalScore) { return (int) totalScore; // may exceed int range } }Considering the given scenario, what error will occur if the value of totalScore exceeds its type range?
  10. What is the output of reversing the array ["apple", "banana", "cherry", "date"] using index-based traversal?
  11. A Student class has methods: void addGrade(double grade) adds one grade; double calculateGPA() returns average grade divided by 25.0. Student s = new Student("Noah") has no grades yet. How does calling s.addGrade(100.0) affect its state?
  12. How does organizing this data into a table, where each row represents a single sighting, aid in planning a program to map the migration path of one specific species?
  13. A mail-sorting machine processes a stack of letters. For each letter, it reads the ZIP code. If the ZIP code is for the local area, the letter is placed in Bin A. Otherwise, it is placed in Bin B. This process continues until the stack is empty. This algorithm combines which two fundamental concepts?
  14. A traffic light cycles through GREEN, YELLOW, RED for a fixed number of cycles. Inputs are cycles and starting state; output is the printed sequence of states. Example input: cycles 1, start GREEN; output: GREEN, YELLOW, RED. Example input: cycles 2, start RED; output: RED, GREEN, YELLOW, RED, GREEN, YELLOW. String state = startState; for (int c = 0; c < cycles; c++) { for (int t = 0; t < 3; t++) { System.out.println(state); if (state.equals("GREEN")) state = "YELLOW"; else if (state.equals("YELLOW")) state = "RED"; else state = "GREEN"; } } Consider the algorithm for the traffic light; what is the time complexity in terms of cycles cc?
  15. In the given program, an ArrayList stores score objects, so it uses Integer rather than primitive int. import java.util.ArrayList; public class ScoreTracker { public static void main(String[] args) { ArrayList<Integer> scores = new ArrayList<>(); // Add scores using the Integer wrapper type scores.add(Integer.valueOf(30)); scores.add(40); // autoboxing System.out.println(scores.get(0)); } }Which of the following is a correct use of the Integer wrapper class in the code?
  16. What is the purpose of the loop in the provided code? // Part A: Setup ArrayList<String> names = new ArrayList<>(); names.add("Alex"); names.add("alex"); names.add("ALEX"); // Part B: Count occurrences (ignore case) int count = 0; for (String name : names) { // traverse list if (name.equalsIgnoreCase("alex")) { count++; } } // Part C: Output System.out.println(count);
  17. A programmer is designing a system to manage a digital music library. Which of the following best exemplifies the concept of data abstraction in this context?
  18. An insertion sort algorithm is processing the array [10, 5, 15, 3, 12]. The algorithm has just completed inserting the element at index 3 (value 3) into its correct position. If the next step processes the element at index 4, how many element shifts will occur during this next insertion?
  19. Which method would you use to replace a book title at a specific index in an ArrayList? import java.util.ArrayList; public class UpdateTitle { public static void main(String[] args) { ArrayList<String> books = new ArrayList<String>(); books.add("OldTitle"); // replace index 0 with "NewTitle" } }
  20. A program for a library needs to track various pieces of information about its books. Which of the following quantities is best represented by an int?

Practice tests