In Java (String references and reassignment), what does this program print? public class StringRef { public static void main(String [] args) { String s1 = "abc"; String s2 = "def"; String s3 = s2; /* Line 7 */ s2 = "ghi"; System.out.println(s1 + s2 + s3); } }
-
Aabcdefghi
-
Babcdefdef
-
Cabcghidef
-
Dabcghighi
-
Eabcghiabc
Answer
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:
s1starts as "abc".s2starts as "def".s3 = s2means both refer to the same "def" at that moment.s2 = "ghi"rebindss2to a new String;s3still 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:
Initially: s1="abc", s2="def" s3 = s2 → s3 refers to "def" s2 = "ghi" → s2 now refers to "ghi" Print: s1 + s2 + s3 = "abc" + "ghi" + "def" = "abcghidef"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:
- "abcdefghi": presumes concatenation in original order without reassignment.
- "abcdefdef": assumes
s2did not change. - "abcghighi": assumes
s3also changed to "ghi".
Common Pitfalls: Assuming Java reassignments perform deep copies; they do not. Variables hold references to objects.
Final Answer: abcghidef