College Board Unit 1
How it works
A String object cannot be modified in place. substring returns a String value while leaving the original contents unchanged, and concatenation also leaves the original objects unchanged. Assigning a result changes which String a variable refers to; it does not edit the old object. equals compares character sequences, while == compares references. Two distinct String objects can therefore have equal contents.
Use a returned value in an assignment, return statement, condition, or other expression. To replace a variable's text, assign the String result to that variable.
Common error
Calling s.substring(1); alone discards the result. Assigning s = s.substring(1); changes s's reference while leaving the original object unchanged.
Worked example
Java
String text = "plane";
text.substring(1);
System.out.println(text);
text = text.substring(1);
System.out.println(text);Output
plane
laneThe first result is discarded. The assignment makes text refer to the returned String.
Exercises
4.3.1 · Trace
Determine the exact output. Explain the Java rule or state changes that produce it.
Java
String a = "cat";
String b = a;
a += "s";
System.out.println(a + ":" + b);Show solution
Output
cats:catReassigning a does not change the immutable object still referenced by b.
4.3.2 · Write code
Given String word = "book" and String saved = word, replace word with its last three characters followed by "!". Print word and saved, separated by a colon.
Show solution
One valid solution is shown below. Other implementations satisfying the contract are also valid.
Java
String word = "book";
String saved = word;
word = word.substring(1) + "!";
System.out.println(word + ":" + saved);