Unit 1 Cycle 2 Day 8: I/II/III: String Behavior
Share
I/II/III: String Behavior
Section 1.10 — Strings: Methods
Key Concept
I/II/III questions about String behavior test common misconceptions. Remember: strings are immutable, so methods like toUpperCase() return a new string without modifying the original. The == operator compares references, not content. substring(a, b) includes index a but excludes index b. indexOf() returns -1 when the target is not found, not 0 or an exception. Each of these properties is a potential trap in an I/II/III question where one plausible-sounding statement violates one of these rules.
Consider the following statements about Strings in Java.
Which of the statements are correct?
Answer: (B) I and III only
Index the string: H(0) E(1) L(2) L(3) O(4)
I: CORRECT. substring(0, 5) returns the entire string "HELLO". Using length() as the end index gives the full string.
II: INCORRECT. indexOf("LO") finds where "LO" starts. L is at index 3, O at index 4. So "LO" starts at index 3, not 2. Index 2 is the first L, but "LO" is not at index 2 because index 2-3 is "LL".
III: CORRECT. substring(5) on a 5-character string returns an empty string "". The start index equals the length, so no characters are included.
Why Not the Others?
(A) Statement II is incorrect. indexOf("LO") returns 3, not 2. The substring "LO" starts at the second L (index 3), not the first L (index 2).
(C) Statement II is incorrect. indexOf finds a matching substring, not just the first occurrence of the first character.
(D) Statement II is the trap. "LO" as a consecutive pair starts at index 3 (L at 3, O at 4), not at index 2 (L at 2, L at 3).
Common Mistake
indexOf matches the entire argument as a consecutive sequence. "HELLO".indexOf("LO") looks for L immediately followed by O. Index 2 has L followed by L (not O), so it continues to index 3 where L is followed by O.
AP Exam Tip
When tracing indexOf with a multi-character argument, check that ALL characters match consecutively at the found position, not just the first character.