AP CSA Unit 1 Day 14: Substring Indexof
Share
substring and indexOf
Section 1.10 — Strings: Methods
Key Concept
The Math.random() method combined with casting and arithmetic enables a wide variety of random generation patterns. For boolean values, Math.random() < 0.5 gives roughly 50/50 odds. To pick a random element from an array, use arr[(int)(Math.random() * arr.length)]. A less obvious pattern: to generate a random even number between 0 and 20, use (int)(Math.random() * 11) * 2. On the AP exam, always trace the formula with boundary values — what happens when Math.random() returns 0.0 and when it returns 0.999?
Consider the following code segment.
What is printed as a result of executing the code segment?
Answer: (A) PUTE
Trace the String operations:
indexOf("PUT"): Find where "PUT" starts in "COMPUTER". Index the characters: C(0) O(1) M(2) P(3) U(4) T(5) E(6) R(7). "PUT" starts at index 3.
substring(3, 7): Since idx = 3, this is substring(3, 3 + 4) = substring(3, 7). This extracts characters at indices 3, 4, 5, 6: "PUTE".
Remember: substring(start, end) includes start but excludes end.
Why Not the Others?
(B) "PUT" is only 3 characters (indices 3-5). But substring(3, 7) extracts 4 characters (indices 3-6). The extra character is 'E' at index 6.
(C) This would require starting at index 2 (the 'M'). But indexOf("PUT") returns 3, not 2. indexOf finds where the pattern starts, which is at 'P'.
(D) "PUTER" has 5 characters, but substring(3, 7) extracts only 4 characters (indices 3 through 6). Index 7 is 'R' but it is excluded.
Common Mistake
Two things to remember: (1) indexOf returns the starting position of the found substring. (2) substring(start, end) includes start but excludes end. The length of the result is always end - start characters.
AP Exam Tip
Write out the string with index numbers above each character before doing any substring or indexOf operation. This prevents off-by-one errors. For example: C(0) O(1) M(2) P(3) U(4) T(5) E(6) R(7).