Predict what this concat snippet prints
Decide what the snippet prints and explain why, in terms of how String behaves.
Constraints:
- reason from
Stringimmutability — do not assumeconcatmutates in place
String a = "qwe";
a.concat("rty");
System.out.println(a);
Determine the output and justify it.
It prints qwe. String is immutable, so concat does not modify a in place — it returns a brand-new String "qwerty". That return value is discarded because it is never assigned, leaving a still pointing at the original "qwe". To keep the result you must assign it: a = a.concat("rty");.
- ✗Believing
concatmutates the receiver string in place - ✗Forgetting that the returned new
Stringis lost when not assigned - ✗Confusing
Stringsemantics with mutableStringBuilder.append
- →How would
StringBuilder.appenddiffer in this same snippet? - →What is the smallest change that makes it print
qwerty?
Walkthrough
String a = "qwe";
a.concat("rty"); // builds a new "qwerty" and... discards it
System.out.println(a); // qwe
String in Java is immutable: no method changes an existing string object. concat creates and returns a new string "qwerty", but the reference a still points at the original "qwe" object. The returned value is never stored, so it is lost.
To get qwerty, assign the result:
a = a.concat("rty"); // a now references "qwerty"
The same holds for trim, toUpperCase, replace, and the rest — they all return a new string rather than mutating the original.