Java pass-by-value with String vs StringBuffer: what concatenated output is printed? public class Test138 {\n public static void stringReplace(String text) { text = text.replace('j', 'c'); }\n public static void bufferReplace(StringBuffer text) { text = text.append("c"); }\n public static void main(String[] args) {\n String textString = new String("java");\n StringBuffer textBuffer = new StringBuffer("java");\n stringReplace(textString);\n bufferReplace(textBuffer);\n System.out.println(textString + textBuffer);\n }\n}

Difficulty: Easy

Correct Answer: javajavac

Explanation:


Introduction / Context:
This tests the behavior difference between immutable String and mutable StringBuffer, plus Java's pass-by-value parameter passing. Assignments inside methods affect only local references unless the object itself is mutated.


Given Data / Assumptions:

  • textString is "java".
  • textBuffer is "java".
  • stringReplace assigns a new String to its local parameter; bufferReplace appends to the passed buffer.


Concept / Approach:
Java passes object references by value. Rebinding a parameter (e.g., text = text.replace(...)) does not change the caller's reference. Mutating the object through the reference (e.g., append) changes the shared object.


Step-by-Step Solution:
stringReplace: creates a new String "cava" but assigns it only to the local parameter; caller's textString remains "java".bufferReplace: appends "c" to the existing StringBuffer; caller sees "javac".Concatenation: "java" + "javac" ⇒ "javajavac".


Verification / Alternative check:
Return the replaced String and assign it to textString to observe "cavajavac". Or in bufferReplace, reassign the parameter to a new buffer and note the caller still references the original.


Why Other Options Are Wrong:
Options A/B/E mis-handle either the immutability of String or the in-place mutation of StringBuffer; Option D is incorrect because code compiles.


Common Pitfalls:
Thinking Java is pass-by-reference for objects; in reality, the reference is passed by value.


Final Answer:
javajavac

More Questions from Java.lang Class

Discussion & Comments

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