Difficulty: Easy
Correct Answer: abcd
Explanation:
Introduction / Context:
This question targets String immutability and the fact that methods like replace return a new String rather than modifying the original instance. Without assignment, the original reference still points to the unchanged String.
Given Data / Assumptions:
Concept / Approach:
In Java, String objects are immutable. Every transformation like toLowerCase, replace, trim, etc., returns a new String. If you do not capture the return, the variable still references the original String. Therefore, b remains "abcd" and is printed as such.
Step-by-Step Solution:
Start: a = "ABCD". b = a.toLowerCase() → b points to "abcd". b.replace('a','d') → returns "dbcd" but the result is ignored. b.replace('b','c') → would return "accd" if applied to "abcd", but again ignored. b still references "abcd". Printing yields "abcd".
Verification / Alternative check:
If you instead wrote b = b.replace('a','d'); b = b.replace('b','c');
, the final output would become "dccd".
Why Other Options Are Wrong:
"ABCD" ignores the toLowerCase assignment; "dccd"/"dcba" assume replacements were stored; any other mix does not follow the immutable semantics.
Common Pitfalls:
Expecting in-place mutation; forgetting to reassign after String operations.
Final Answer:
abcd
Discussion & Comments