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
Discussion & Comments