Unit 2 Cycle 2 Day 25: I/II/III: String Traversal Patterns
Share
I/II/III: String Traversal Patterns
Section 2.11 — String Traversal
Key Concept
I/II/III string traversal pattern questions test whether you understand different approaches to processing strings. Common patterns include: forward traversal counting characters, backward traversal building reversed strings, and traversal with lookahead checking charAt(i+1). Each pattern has different boundary requirements. Forward traversal uses i < length(), backward uses i >= 0, and lookahead must stop at length() - 1 to avoid an out-of-bounds error. The AP exam asks which patterns correctly implement a specific string operation.
Consider the following code applied to String s = "racecar".
Which of the statements are correct?
Answer: (D) I, II, and III
s = "racecar": r(0) a(1) c(2) e(3) c(4) a(5) r(6).
I: substring(0,1)="r", substring(6)="r". "r".equals("r") = true.
II: charAt(3)='e', 'e'=='e' = true (always true comparing a value to itself).
III: indexOf("car") finds "car" at index 4 (c=4, a=5, r=6). true.
Why Not the Others?
(A) Statement III is also correct. "car" starts at index 4 in "racecar".
(B) Statement I is also correct. Both endpoints of the palindrome are "r".
(C) Statement II is also correct. Any value equals itself.
Common Mistake
Statement II is trivially true (comparing a value to itself). Statement I tests the first and last characters. Statement III requires finding the substring position. "racecar" is a palindrome, which is why the first and last characters match.
AP Exam Tip
For I/II/III questions, evaluate each statement completely. Do not assume a statement is false just because it looks too simple (like II).