Question 231
Consider the following class and client code.
public class Tank {
private int level;
private int capacity;
public Tank(int cap) { capacity = cap; level = 0; }
public int fill(int amount) {
int space = capacity - level;
if (amount <= space) { level += amount; return 0; }
else { level = capacity; return amount - space; }
}
public int drain(int amount) {
if (amount <= level) { level -= amount; return amount; }
else { int drained = level; level = 0; return drained; }
}
public int getLevel() { return level; }
}
// Client:
Tank t1 = new Tank(50);
Tank t2 = new Tank(30);
int overflow = t1.fill(45);
overflow += t1.fill(20);
int got = t1.drain(overflow);
t2.fill(got);
System.out.println(t1.getLevel() + " " + t2.getLevel());What is printed?
Main Solution
Step-by-step trace:
Setup:
t1 = new Tank(50)→ t1.level = 0, t1.capacity = 50t2 = new Tank(30)→ t2.level = 0, t2.capacity = 30
Line: int overflow = t1.fill(45);
- space = 50 - 0 = 50
- 45 <= 50, so level += 45 → t1.level = 45; return 0
- overflow = 0
Line: overflow += t1.fill(20);
- space = 50 - 45 = 5
- 20 > 5, so level = 50 (capacity); return 20 - 5 = 15
- t1.level = 50; overflow = 0 + 15 = 15
Line: int got = t1.drain(overflow); (overflow = 15)
- 15 <= 50, so level -= 15 → t1.level = 35; return 15
- got = 15
Line: t2.fill(got); (got = 15)
- space = 30 - 0 = 30
- 15 <= 30, so level += 15 → t2.level = 15; return 0
Line: System.out.println(t1.getLevel() + " " + t2.getLevel());
- t1.getLevel() = 35, t2.getLevel() = 15
- Prints: 35 15
The correct answer is B.
Teacher Explanation
This question tests students' ability to trace through object method calls that modify instance variables and return values. Key skills: tracking level state across multiple fill and drain calls, correctly computing overflow (amount - space when overfilling), and understanding that drain returns the amount actually drained. Students must carefully accumulate overflow across two fill calls before draining.
Education Coach Advice
AP Exam Strategy: For code-tracing questions, create a small table tracking each variable after every line. Here: track t1.level, t2.level, overflow, and got. Pay special attention to methods that both modify state AND return a value — both effects matter. Don't skip the += accumulation step for overflow.
Traps
Common traps:
- Option A (45 0): Students may forget that
overflowaccumulates across bothfillcalls, or may not realize the secondfill(20)causes overflow. They might thinkoverflowstays 0 andgot = 0, so t2 gets nothing. - Option C (50 15): Students may correctly compute t2.level = 15 but forget that
drain(15)reduces t1.level from 50 to 35, leaving t1 at 50. - Option D (35 30): Students may think
got = 30(confusing it with t2's capacity) and fill t2 to capacity.
Answer images

