Unit 1 Cycle 1 Day 15: Chained String Methods
Share
Chained String Methods
Section 1.10 — Strings: Methods
Key Concept
Object creation in Java uses the new keyword followed by a constructor call. The constructor initializes the object's state by setting instance variable values. A class can have multiple constructors (overloading) as long as they have different parameter lists. If no constructor is defined, Java provides a default no-argument constructor that sets numeric fields to 0, booleans to false, and references to null. Once you define any constructor, the default is no longer provided — this is a common source of compile errors on the AP exam.
Consider the following code segment.
What is printed as a result of executing the code segment?
Answer: (B) VA PR5
Trace step by step:
indexOf("A"): Finds the first "A" in "JAVA PRACTICE" at index 1.
indexOf("A") + 1: 1 + 1 = 2.
substring(2, 8): Characters at indices 2-7: "VA PR" (J(0) A(1) V(2) A(3) (4)P(5) R(6) ... wait, let me recount). J(0) A(1) V(2) A(3) ␣(4) P(5) R(6) A(7) C(8)... indices 2 through 7 = "VA PR". Actually: index 2=V, 3=A, 4=space, 5=P, 6=R. That is 5 characters: "VA PR".
part.length(): "VA PR" has 5 characters.
Concatenation: "VA PR" + 5 = "VA PR5".
Why Not the Others?
(A) This assumes substring(2, 8) includes index 8 and gets 7 characters. The end index is exclusive, so only indices 2-7 are included (5 characters).
(C) This starts at index 1 (indexOf("A")) instead of index 2 (indexOf("A") + 1). The + 1 shifts the start forward.
(D) Same start error as (C), beginning at index 1 instead of 2.
Common Mistake
Two traps: (1) indexOf("A") returns the first occurrence at index 1, not the one at index 3 or 7. (2) The end index in substring(start, end) is exclusive. Also, spaces count as characters.
AP Exam Tip
Write out the string with index numbers: J(0) A(1) V(2) A(3) ␣(4) P(5) R(6) A(7) C(8) T(9) I(10) C(11) E(12). This makes substring operations visual and accurate.