Question 261
Consider the following class and client code.
public class TextEditor {
private String text;
public TextEditor(String t) { text = t; }
public String replaceFirst(String target, String replacement) {
int pos = text.indexOf(target);
if (pos == -1) return text;
text = text.substring(0, pos) + replacement
+ text.substring(pos + target.length());
return text;
}
public String getText() { return text; }
}
// Client:
TextEditor ed = new TextEditor("abcabcabc");
ed.replaceFirst("bc", "X");
ed.replaceFirst("bc", "Y");
System.out.println(ed.getText());What is printed?
Main Solution
Step-by-step trace:
Initial state: text = "abcabcabc"
First call: ed.replaceFirst("bc", "X")
pos = text.indexOf("bc")→pos = 1(first occurrence of "bc" is at index 1 in "abcabcabc")text = text.substring(0, 1) + "X" + text.substring(1 + 2)text = "a" + "X" + "abcabc"text = "aXabcabc"
Second call: ed.replaceFirst("bc", "Y")
pos = text.indexOf("bc")on"aXabcabc"→ "bc" first appears at index 3text = text.substring(0, 3) + "Y" + text.substring(3 + 2)text = "aXa" + "Y" + "abc"text = "aXaYabc"
Output: System.out.println(ed.getText()) prints aXaYabc.
The correct answer is A.
Teacher Explanation
This question tests students' ability to trace mutable state through method calls. The key insight is that replaceFirst modifies the instance variable text in place (it is not a pure function). Each subsequent call operates on the already-modified string, not the original. Students must carefully track the evolving value of text after each call.
Education Coach Advice
AP Exam Strategy: When tracing code with mutable instance variables, write down the value of each variable after every statement. Do not assume a method returns a new object — check whether it modifies the original. For String methods like substring and indexOf, remember that indices are 0-based and substring(a, b) excludes index b. Slow, careful tracing prevents index-off-by-one errors.
Traps
Common traps:
- Option B (XYabcabc): Students may think the first replacement starts at index 0, replacing "ab" instead of finding "bc" at index 1. This misreads
indexOf. - Option C (aXabYabc): Students may forget that the first call mutates
text, and incorrectly apply the second replacement to the original string "abcabcabc", finding "bc" at index 4 of the original rather than index 3 of the updated string. - Option D (aXaYbc): Students may miscalculate the substring after the second replacement, dropping the trailing "abc" or miscounting indices.
Answer images

