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

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