Question 951
What is printed?
ArrayList<String> words = new ArrayList<String>();
words.add("cat"); words.add("dog"); words.add("car");
words.add("dot"); words.add("cup");
ArrayList<String> result = new ArrayList<String>();
for (int i = 0; i < words.size(); i++) {
String w = words.get(i);
if (w.substring(0, 1).equals("c")) {
result.add(w);
}
}
for (int i = result.size() - 1; i >= 0; i--) {
if (result.get(i).indexOf("a") != -1) {
result.remove(i);
}
}
System.out.println(result);Main Solution
Step 1: Build the words list.
words = ["cat", "dog", "car", "dot", "cup"]
Step 2: First loop — collect words starting with "c".
We iterate through words and check w.substring(0, 1).equals("c"):
- "cat" → starts with 'c' → added
- "dog" → starts with 'd' → skipped
- "car" → starts with 'c' → added
- "dot" → starts with 'd' → skipped
- "cup" → starts with 'c' → added
After first loop: result = ["cat", "car", "cup"]
Step 3: Second loop — iterate backwards and remove words containing "a".
We iterate from i = result.size() - 1 = 2 down to i = 0, removing any element where indexOf("a") != -1:
i = 2:result.get(2)= "cup" →"cup".indexOf("a")= -1 → NOT removedi = 1:result.get(1)= "car" →"car".indexOf("a")= 1 ≠ -1 → removed.result = ["cat", "cup"]i = 0:result.get(0)= "cat" →"cat".indexOf("a")= 1 ≠ -1 → removed.result = ["cup"]
Step 4: Print result.
System.out.println(result) prints the ArrayList's toString(), which is [cup].
The correct answer is D: [cup].
Teacher Explanation
This question tests two key skills: (1) iterating an ArrayList and filtering by string methods (substring, equals), and (2) safely removing elements from an ArrayList by iterating backwards. The backwards iteration avoids index-skipping issues. Words starting with 'c' are: "cat", "car", "cup". Then any of those containing 'a' ("cat" and "car") are removed, leaving only "cup".
Education Coach Advice
When tracing ArrayList removal loops, always simulate the index changes step by step. Backwards iteration is the safe pattern — it avoids skipping elements. For each iteration, write down the current state of the list and the current index. Also remember that indexOf returns -1 when the substring is NOT found, so != -1 means the substring IS present.
Traps
Option A [cat, car, cup]: A student might think the second loop does nothing, perhaps misreading the condition or thinking indexOf returns 0 for not found. Option B [cat, cup]: A student might think only "car" is removed (perhaps iterating forward and skipping "cat" after "car" is removed, which would actually skip "cup" — this trap is subtle). Option C [car, cup]: A student might think only "cat" is removed, perhaps confusing the condition or only checking the first character. The key insight is that BOTH "cat" and "car" contain the letter 'a', so both are removed, leaving only "cup".
Answer images

