AP CSA Unit 1 Day 15: Object State Change
Share
Advanced Practice Question
String word = "science";
word.substring(0, 3);
word.substring(4);
System.out.println(word);
System.out.println(word.length());
String objects are immutable in Java. Once a String is created, it cannot be changed.
Methods like substring() do not modify the original String. They return a new String with the result. If the return value is never assigned to a variable, it is simply thrown away.
Line 1: word = "science"
Line 2: word.substring(0, 3) → creates and returns "sci", but the result is never stored. word is still "science".
Line 3: word.substring(4) → creates and returns "nce", but again the result is never stored. word is still "science".
Lines 4-5: Prints "science" then 7 (the length of "science").
To actually change word, you must reassign: word = word.substring(0, 3);
A) sci / 3 — Assumes substring(0, 3) modifies the original String. It does not. The return value was discarded because it was never assigned.
C) nce / 3 — Assumes the second substring(4) modifies the original String, and also assumes the first call already changed it. Neither call changes word.
D) scince / 6 — Assumes both substring calls somehow combined to remove a character from the middle. String methods never modify the original — they always return a new String.
This is one of the most common AP exam traps. When you see a String method called without its return value being stored (str.substring(0, 3); instead of str = str.substring(0, 3);), the original String is completely unchanged. The method still runs and creates a new String, but that new String is immediately garbage collected because nothing references it.
Immutability rule: No String method ever modifies the String it is called on. Look for the pattern variable = variable.method(...); — the reassignment is required for any change to take effect. If there is no = sign capturing the return value, the String has not changed. This pattern appears on nearly every AP exam.
Keep Building Mastery!
Cycle 2 questions prepare you for the hardest AP CSA exam questions.
Study Games Practice FRQs