Difficulty: Easy
Correct Answer: abcghidef
Explanation:
Introduction / Context:
The question demonstrates how Java variable assignment with immutable Strings copies references, not contents, and how later reassignment of one reference does not change the object referenced by another variable captured earlier.
Given Data / Assumptions:
s1
starts as "abc".s2
starts as "def".s3 = s2
means both refer to the same "def" at that moment.s2 = "ghi"
rebinds s2
to a new String; s3
still refers to "def".
Concept / Approach:
Java Strings are immutable; assignment does not clone data. Reassigning s2
changes only which object s2
points to. The original object "def" remains, and s3
still points to it.
Step-by-Step Solution:
Verification / Alternative check:
If we had modified contents (which is impossible with immutable Strings), only then would s3
reflect such changes. With mutable types (e.g., StringBuilder), sharing a reference and then mutating would affect all aliases.
Why Other Options Are Wrong:
s2
did not change.s3
also changed to "ghi".
Common Pitfalls:
Assuming Java reassignments perform deep copies; they do not. Variables hold references to objects.
Final Answer:
abcghidef
Discussion & Comments