Practice Test 9 - AP Computer Science A
20 questions. Answer them in any order, then submit to see your score and every explanation.
- A game clamps score after adding a bonus:
class ScoreKeeper { public static int safeAdd(int score, double bonus) { int added = (int) bonus; // may be large int total = score + added; // overflow risk return total; } }Which line of code will cause a problem due to range limitations? - Based on the example code, data collections require object types, so scores use wrappers instead of primitives.
import java.util.ArrayList; public class ScoreTracker { public static void main(String[] args) { ArrayList<Integer> scores = new ArrayList<>(); // Integer wrapper stores score objects in the list scores.add(7); scores.add(13); System.out.println(scores.size()); } }What is the purpose of using wrapper classes in this scenario? - Given the Counter class above, after executing the following code sequence, what will be the output of the final println statement? Counter c1 = new Counter(); Counter c2 = new Counter(5); c1.increment(); c1.increment(); System.out.println(c1.getValue() + " " + Counter.getTotalCounters());
- Based on the class design for the online store, which method signature correctly implements calculating a percentage discount on a Product price?
- In student records, a StudentRecord class stores studentId and grades to protect sensitive data. The counselor app calls updateGrade to change grades through validation rules. A protected method computeGpa aggregates grades for reports without exposing raw calculations. What is the outcome if grades is changed from private to public?
- What is the time complexity of this recursive merge sort on an array of size ?
public class Sorter { public static void mergeSort(int[] nums, int left, int right) { if (left >= right) { return; } int mid = (left + right) / 2; mergeSort(nums, left, mid); mergeSort(nums, mid + 1, right); 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 programmer is designing a
BankAccountclass that must enforce the principle that account balances can never go below zero. The class should allow deposits, withdrawals (only if sufficient funds exist), and balance inquiries. Which design approach best demonstrates proper abstraction and encapsulation for this requirement? - Refer to the Student class code below: how does the parameterized constructor differ from the one-parameter constructor?
public class Student { private String name; private int id; // Public constructor: sets name only and defaults id. public Student(String name) { this(name, 0); } // Public parameterized constructor: sets both name and id. public Student(String name, int id) { this.name = name; this.id = id; } // Private constructor: blocks creating a student with no data. private Student() { this("Unknown", 0); } } - A Book class has methods: void checkOut() sets checkedOut to true; void returnBook() sets checkedOut to false; boolean isCheckedOut() returns checkedOut. Book novel = new Book("Dune") starts not checked out. How does calling novel.checkOut() affect its state?
- A social media platform analyzes user engagement data stored in an ArrayList<Integer> representing daily post likes. The platform wants to identify the longest consecutive sequence of days where likes increased compared to the previous day. Which approach correctly identifies this pattern?
- Based on standard object-oriented design principles, the italicized nouns in the description are most likely to be modeled as which of the following program components?
- What is the defining characteristic of repetition in an algorithm?
- In access control, hasValidCredentials and isAccountActive are used:
if (hasValidCredentials) if (isAccountActive) result = "LOGIN" else result = "INACTIVE" else result = "FAIL"What does the Boolean expression hasValidCredentials && !isAccountActive signify in the provided code? - In an object-oriented bank account program, methods are behaviors that operate on an object's stored data. For example, deposit updates the private balance:
public void deposit(double amount) { balance += amount; }Refer to the example in the text, what doesamountrepresent whena.deposit(25.0)is called? - A variable of type
booleanis capable of storing which of the following sets of values? - A traffic light simulation prints states for a total duration in seconds, changing every 5 seconds. Inputs are totalSeconds and startState; output is the printed state at each second. Example input: total 6, start GREEN; output: GREEN printed 5 times, then YELLOW once. Example input: total 5, start RED; output: RED printed 5 times.
String state = startState; for (int s = 1; s <= totalSeconds; s++) { System.out.println(state); if (s % 5 == 0) { 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 output after totalSeconds = 5, startState = GREEN? - A programmer is designing a class hierarchy for a game with different types of weapons. Each weapon has damage, range, and durability, but different weapon types calculate damage differently. The programmer considers: (1) an abstract Weapon class with concrete subclasses, or (2) a concrete Weapon class with a weaponType field and switch statements. Which statement best analyzes the impact of these design choices on code flexibility and testing?
- Game Development: Given the code snippet, how would you modify the array scores to add one more element?
public class AddPlayerScore { public static void main(String[] args) { // Scores for three players int[] scores = {300, 450, 500}; // int array: player scores System.out.println(scores[2]); // access last score } } - Consider the following class for student records. The StudentRecord class has addGrade(double points) and calculateGpa(int numClasses) that returns totalPoints / numClasses. It also has getName() that returns the student name. A program instantiates StudentRecord r = new StudentRecord("Liam"); then calls r.addGrade(9.0). The expected output of calculateGpa depends on the parameter value. If calculateGpa(3) is called, what is the expected result?
- In the given program, collections store objects, so scores use wrappers not primitives.
import java.util.ArrayList; public class ScoreTracker { public static void main(String[] args) { ArrayList<Integer> scores = new ArrayList<>(); // Add primitive int values; autoboxing wraps them as Integer scores.add(10); scores.add(25); int total = scores.get(0) + scores.get(1); // unboxing for addition System.out.println(total); } }How does autoboxing work in the given example?