1Z0-808 · Question #57
Given: public static void main(String[] args) { String ta = "A"; ta = ta.concat("B"); String tb = "C"; ta = ta.concat(tb); ta.replace('C', 'D'); System.out.println(tb); System.out.println(ta); }…
The correct answer is C. A B D. Option C is correct because Java Strings are immutable - ta.replace('C', 'D') returns a new String "ABD" but since the result is never assigned back to ta, that new object is immediately discarded. Tracing the code: ta becomes "AB" after the first concat, then "ABC" after the…
Question
Options
- AA B C D
- BA C D
- CA B D
- DA B D C
- EA B D C
How the community answered
(43 responses)- A14% (6)
- B2% (1)
- C74% (32)
- D7% (3)
- E2% (1)
Explanation
Option C is correct because Java Strings are immutable - ta.replace('C', 'D') returns a new String "ABD" but since the result is never assigned back to ta, that new object is immediately discarded. Tracing the code: ta becomes "AB" after the first concat, then "ABC" after the second (both results are reassigned), while tb remains "C" throughout - giving output "C" then "ABC".
Choices A, B, D, and E all include 'D' in the output, which would only appear if replace() mutated ta in place - the classic mistake this question is designed to catch. Choices D and E are identical and both wrong for the same reason. Choice B drops 'B' entirely, which makes no sense given the explicit concat("B") assignment.
Memory tip: In Java, String methods never change the original - they return a new String. If you don't catch the return value, the result disappears. Think: ta = ta.replace(...), not just ta.replace(...).
Topics
Community Discussion
No community discussion yet for this question.