Java Strings are immutable: after toLowerCase and unused replace calls, what exactly is printed?\n\nString a = 'ABCD';\nString b = a.toLowerCase();\nb.replace('a', 'd');\nb.replace('b', 'c');\nSystem.out.println(b);

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:

  • a = "ABCD".
  • b = a.toLowerCase() → "abcd".
  • Two calls to b.replace(...) are made, but their returned values are not stored.
  • System.out.println(b) prints the current object referenced by b.


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

More Questions from Java.lang Class

Discussion & Comments

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