In Java, what will be the output of this program demonstrating String immutability and parameter passing? class PassS { public static void main(String [] args) { PassS p = new PassS(); p.start(); } void start() { String s1 = "slip"; String s2 = fix(s1); System.out.println(s1 + " " + s2); } String fix(String s1) { s1 = s1 + "stream"; System.out.print(s1 + " "); return "stream"; } }

Difficulty: Medium

Correct Answer: slipstream slip stream

Explanation:


Introduction / Context:
This program highlights two concepts: Java passes object references by value, and java.lang.String is immutable. Reassigning the parameter inside the method does not change the caller’s variable.



Given Data / Assumptions:

  • start(): s1 = "slip".
  • fix(s1) concatenates "stream" to its local parameter and prints it, then returns "stream".
  • After the call, main prints s1 and s2.


Concept / Approach:
Inside fix, s1 = s1 + "stream" creates a new String "slipstream". The original reference in start() still points to "slip" because Strings are immutable and the parameter is a local copy of the reference. The method also returns the literal "stream".



Step-by-Step Solution:

Before call: s1 → "slip".Inside fix: local s1 → "slipstream"; prints "slipstream ".fix returns "stream".Back in start: s1 still "slip"; s2 = "stream".Prints: "slip stream" (after the earlier "slipstream ").


Verification / Alternative check:
Replace String with a mutable type like StringBuilder and modify contents; then the change would be visible to the caller.



Why Other Options Are Wrong:
They presume the original s1 mutates in the caller or misorder the prints.



Common Pitfalls:
Assuming Java passes objects by reference; misunderstanding String immutability; overlooking the print order (first from fix, then from start).



Final Answer:
slipstream slip stream

More Questions from Operators and Assignments

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion