Question 271
Consider the following class and client code. What is printed?
public class Accumulator {
private int total;
private int count;
private int limit;
public Accumulator(int lim) { total = 0; count = 0; limit = lim; }
public boolean add(int val) {
if (total + val > limit) { return false; }
total += val;
count++;
return true;
}
public int getAverage() {
if (count == 0) { return 0; }
return total / count;
}
}
// Client:
Accumulator acc = new Accumulator(50);
acc.add(15);
acc.add(20);
acc.add(10);
boolean b = acc.add(8);
System.out.println(acc.getAverage() + " " + b);Main Solution
Step-by-step trace:
The Accumulator is created with limit = 50, total = 0, count = 0.
acc.add(15): Check0 + 15 > 50? No. Sototal = 15,count = 1, returnstrue.acc.add(20): Check15 + 20 > 50? No. Sototal = 35,count = 2, returnstrue.acc.add(10): Check35 + 10 > 50? No (45 ≤ 50). Sototal = 45,count = 3, returnstrue.acc.add(8): Check45 + 8 > 50? Yes (53 > 50). So returnfalseimmediately —totalandcountare NOT updated.b = false.
getAverage(): count = 3 (not 0), so return total / count = 45 / 3 = 15.
Output: 15 false → Answer C.
Teacher Explanation
This question tests students' ability to trace through an object's state across multiple method calls, paying attention to early return statements. The key insight is that when add(8) is called, the guard condition total + val > limit (45 + 8 = 53 > 50) is true, so the method returns false without modifying total or count. Integer division then gives 45/3 = 15.
Education Coach Advice
AP Exam Strategy: When tracing code with conditional return statements, always check the guard condition first before updating any state. Draw a small table tracking each instance variable (total, count) after each method call. Remember that integer division in Java truncates toward zero — always compute the exact quotient and drop the remainder.
Traps
Common traps:
- Option D (15 true): Students may forget that 45 + 8 = 53 exceeds the limit of 50, causing
add(8)to returnfalse. They might assume all four adds succeed. - Option B (16 false): Students might include the 8 in the total (total = 53, count = 4, 53/4 = 13 — actually not 16 either), or miscalculate the average by dividing by 4 instead of 3 (45/4 = 11 in integer division). Some may compute 63/4 or other wrong totals.
- Option A (12 true): Likely from computing 45/4 = 11 (integer division) or some other miscounting, combined with wrong boolean.
Answer images

