AP CSA Unit 1 Day 7: Object State Over Time Via Methods

Unit 1, Sections 1.9-1.10 • Cycle 2
Day 7 Advanced Practice • Harder Difficulty Hard
Focus: Tracing chained String method calls

Advanced Practice Question

Consider the following code segment. What is printed?
String s = "COMPUTER";
String t = s.substring(0, 4);
String u = t + s.substring(6);
int x = u.indexOf("ER");
System.out.println(u + " " + x);
Why This Answer?

Trace each line using the String methods from the Java Quick Reference:

Line 1: s = "COMPUTER"

  Indices: C=0, O=1, M=2, P=3, U=4, T=5, E=6, R=7

Line 2: t = s.substring(0, 4) → characters at indices 0, 1, 2, 3 → "COMP"

Remember: substring(start, end) includes start but excludes end.

Line 3: s.substring(6) → characters from index 6 to the end → "ER"

  → u = "COMP" + "ER" = "COMPER"

Line 4: u.indexOf("ER") → searches "COMPER" for "ER"

  Indices of u: C=0, O=1, M=2, P=3, E=4, R=5

  → "ER" starts at index 4 in "COMPER"

Output: COMPER 4

Why Not the Others?

B) COMPUTER 6 — This assumes substring(0, 4) includes index 4 (the 'U'). It does not — the end index is exclusive. Also, indexOf would search the wrong string.

C) COMPER 6 — Gets the string correct but searches for "ER" in the original "COMPUTER" (index 6) instead of in "COMPER" (index 4). The indexOf is called on u, not s.

D) COMP 4 — Forgets the concatenation on line 3 and incorrectly assumes u is just "COMP".

Common Mistake
Watch Out!

Two critical traps here: (1) substring(0, 4) returns 4 characters at indices 0-3, not 0-4. The end index is always exclusive. (2) indexOf searches the String it is called on (u), not the original String (s). Students who get "COMPER" correct but answer 6 are searching the wrong variable.

AP Exam Strategy

When tracing String problems, write out the index numbers above each character. For substring(a, b), circle characters from index a up to (but not including) index b. For indexOf, always verify which String you are searching — the AP exam loves to test whether you track which variable holds which value.

Keep Building Mastery!

Cycle 2 questions prepare you for the hardest AP CSA exam questions.

Study Games Practice FRQs
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.