nerdexam
Oracle

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…

Working With Java Data Types

Question

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); } What is the result?

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)
  • A
    14% (6)
  • B
    2% (1)
  • C
    74% (32)
  • D
    7% (3)
  • E
    2% (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

#String immutability#String.concat()#String.replace()#variable references

Community Discussion

No community discussion yet for this question.

Full 1Z0-808 Practice