AP Computer Science A Unit 3 practice questions
Try 10 multiple-choice questions from Unit 3 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
Consider the following class definition and
mainmethod:</>Javapublic class NumberModifier { public static void modify(int a, int b) { a = a * 2; b = b - 3; System.out.print(a + " " + b + " "); } public static void main(String[] args) { int a = 4; int b = 8; modify(a, b); System.out.print(a + " " + b); } }What is printed as a result of executing the
mainmethod?The program executes successfully and prints the exact sequence: 8 5 4 8
The program executes successfully and prints the exact sequence: 8 5 8 5
The program executes successfully and prints the exact sequence: 4 8 8 5
The program executes successfully and prints the exact sequence: 4 8 4 8
Show answer
Answer: (A)
Tracing the method call requires understanding pass-by-value semantics. When
modify(4, 8)is called, the local parametersaandbare initialized to 4 and 8. Inside the method, localabecomes 8 and localbbecomes 5, printing "8 5 ". Because Java passes primitives by value, the original variablesaandbinmainremain unchanged. Themainmethod then prints "4 8".Question 2
Consider the following code segment:
</>Javapublic class LoopReturn { public static int processLoop(int limit) { int sum = 0; for (int k = 1; k <= limit; k++) { sum += k; if (sum >= 6) { return sum; } } return sum; } public static void main(String[] args) { System.out.print(processLoop(5)); } }What is printed as a result of executing the
mainmethod?The method halts early and returns 6 after three loop iterations
The method halts early and returns 3 after three loop iterations
The method completes all loops and returns 15 after five iterations
The method completes all loops and returns 10 after four iterations
Show answer
Answer: (A)
Tracing the loop step-by-step reveals the execution flow. On iteration 1 (
k=1),sumbecomes 1. On iteration 2 (k=2),sumbecomes 3. On iteration 3 (k=3),sumbecomes 6. The conditionsum >= 6evaluates to true, triggering thereturnstatement. Thereturnkeyword immediately halts method execution and outputs 6, preventing further iterations.Question 3
Consider the following class definition and
mainmethod:</>Javapublic class ScoreTracker { private int score = 10; public void updateScore(int score) { score = score + 5; this.score = this.score + score; } public void printScore() { System.out.print(score); } public static void main(String[] args) { ScoreTracker game = new ScoreTracker(); game.updateScore(4); game.printScore(); } }What is printed as a result of executing the
mainmethod?The program will output the final integer value 19 to the console
The program will output the final integer value 30 to the console
The program will output the final integer value 10 to the console
The program will output the final integer value 25 to the console
Show answer
Answer: (A)
Tracing variable scope is required to determine the output. The instance variable
scoreis initialized to 10. WhenupdateScore(4)is called, the local parameterscoreshadows the instance variable. The statementscore = score + 5updates the local parameter to 9. The statementthis.score = this.score + scoreadds the instance variable (10) and the local parameter (9), updating the instance variable to 19.Question 4
The following method is intended to return the number of times the digit
dappears in the positive integernum.</>Javapublic int countDigit(int num, int d) { int count = 0; while (num > 0) { /* missing code */ } return count; }Which of the following can replace
/* missing code */so the method works as intended?if (num % 10 == d) { count++; } num /= 10;if (num % 10 == d) { count++; } num %= 10;if (num / 10 == d) { count++; } num /= 10;if (num / 10 == d) { count++; } num %= 10;Show answer
Answer: (A)
Identifying the correct use of the modulo operator to isolate the last digit and integer division to reduce the number. The condition
num % 10 == dcorrectly checks the rightmost digit, andnum /= 10properly removes it for the next iteration.Question 5
The method
hasEvenDigitis intended to returntrueif the positive integerncontains at least one even digit, andfalseotherwise.</>Javapublic boolean hasEvenDigit(int n) { while (n > 0) { int digit = n % 10; /* missing code */ n /= 10; } return false; }Which of the following can replace
/* missing code */so the method works as intended?if (digit % 2 == 0) { return true; }if (digit % 2 != 0) { return false; }if (digit / 2 == 0) { return true; }if (digit / 2 != 0) { return false; }Show answer
Answer: (A)
Recognizing that returning
trueimmediately upon finding an even digit correctly satisfies the 'at least one' condition. The loop will exit early if an even digit is found, and only returnfalseif all digits are checked and none are even.Question 6
A class contains a method intended to calculate and return the exact decimal average of two integer parameters,
aandb. Which of the following method headers and return statements correctly implements this behavior?public double getAvg(int a, int b) { return (a + b) / 2.0; }public double getAvg(int a, int b) { return (a + b) / 2; }public double getAvg(int a, int b) { return a + b / 2.0; }public int getAvg(int a, int b) { return (a + b) / 2; }Show answer
Answer: (A)
Applying proper type casting and operator precedence to achieve exact decimal division. Dividing the sum by the double literal
2.0forces floating-point division, preventing the truncation of the decimal portion.Question 7
A library charges a late fee of $0.50 per day for the first 10 days a book is late, and $1.00 per day for each day after that. The method
calculateFeeis intended to return the total fee for a book that isdaysLatedays late.</>Javapublic double calculateFee(int daysLate) { if (daysLate <= 0) { return 0.0; } /* missing code */ }Which of the following can replace
/* missing code */so the method works as intended?if (daysLate <= 10) return daysLate * 0.5; return 5.0 + (daysLate - 10) * 1.0;if (daysLate <= 10) return daysLate * 0.5; return 5.0 + (daysLate) * 1.0;if (daysLate <= 10) return daysLate * 0.5; return 0.0 + (daysLate) * 1.0;if (daysLate >= 10) return daysLate * 0.5; return 5.0 + (daysLate - 10) * 1.0;Show answer
Answer: (A)
Translating a piecewise mathematical function into conditional logic. The code correctly calculates the base fee for the first 10 days and adds $1.00 only for the days exceeding the initial 10-day period.
Question 8
The
Counterclass is intended to maintain a running total. TheaddValuemethod is intended to add the parametervalueto the instance variablevalue.</>Javapublic class Counter { private int value; public void addValue(int value) { /* missing code */ } }Which of the following code segments can replace
/* missing code */so that the method works as intended?this.value += value;value += this.value;value = value + value;this.value += this.value;Show answer
Answer: (A)
Recognizing that the
thiskeyword is required to access the instance variable when a parameter has the same name. The code correctly adds the parametervalueto the instance variablethis.value.Question 9
Consider the following class declaration.
</>Javapublic class Book { private String author; private int pages; public Book(String a, int p) { author = a; pages = p; } public String getAuthor() { return author; } public static boolean isSameAuthor(Book b1, Book b2) { return b1.getAuthor().equals(b2.getAuthor()); } }Which of the following best describes the behavior of the
isSameAuthormethod?It is a class method that returns
trueif the twoBookparameters have the exact sameauthorinstance variable value.It is an instance method that returns
trueif the twoBookparameters have the exact sameauthorclass variable value.It is a class method that returns
trueif the twoBookparameters have the exact samepagesinstance variable value.It is an instance method that returns
trueif the twoBookparameters have the exact samepagesclass variable value.Show answer
Answer: (A)
Identifying method and variable types based on the
statickeyword. TheisSameAuthormethod is declaredstatic, making it a class method, and it accesses theauthorinstance variable of the passed objects via their getter methods.Question 10
Consider the following class declaration and code segment.
</>Javapublic class Server { private static int activeConnections = 0; private static final int MAX_CONNECTIONS = 3; private boolean isConnected = false; public static boolean canConnect() { return activeConnections < MAX_CONNECTIONS; } public void connect() { if (canConnect() && !this.isConnected) { this.isConnected = true; activeConnections++; } } } /* * The following code segment appears in a method in another class. */ Server s1 = new Server(); Server s2 = new Server(); Server s3 = new Server(); Server s4 = new Server(); s1.connect(); s2.connect(); s3.connect(); s4.connect(); s1.connect();Which of the following best describes the state of the objects after the code segment executes?
Three
Serverobjects successfully connect, one fails to connect, and the class variableactiveConnectionsevaluates to 3.Four
Serverobjects successfully connect, none fail to connect, and the class variableactiveConnectionsevaluates to 4.Three
Serverobjects successfully connect, one fails to connect, and the instance variableactiveConnectionsevaluates to 3.Four
Serverobjects successfully connect, none fail to connect, and the instance variableactiveConnectionsevaluates to 4.Show answer
Answer: (A)
Tracing the execution of instance methods that interact with shared class variables. Because
activeConnectionsisstatic, it is shared across allServerinstances. The first three calls toconnect()increment the shared counter to 3. The fourth call fails becausecanConnect()returns false, leaving three connected servers and the class variable at 3.
What's on the AP Computer Science A Unit 3 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 1 – Methods and Control Structures (23 minutes)
- 1 FRQ – FRQ 2 – Class Design (23 minutes)
Questions are drawn from 681 multiple-choice questions and 31 FRQs written for Unit 3, Class Creation.
Practice AP Computer Science A Unit 3 FRQs
Answer the unit's free-response questions one at a time and get a score on every part.
- FRQ 1 – Methods and Control Structures (6 questions)
- FRQ 2 – Class Design (25 questions)
Review Unit 3 before you start
- 3.1 Abstraction and Program Design
- 3.2 Impact of Program Design
- 3.3 Anatomy of a Class
- 3.4 Constructors
- 3.5 Writing Methods
- 3.6 Accessor Methods
- 3.7 Static Variables and Methods
- 3.8 Scope and Access
- 3.9 This Keyword