QuestionQ30

Working with Selected Classes from the Java API

Given the following code:

Question Image

What is the result?

  • A A B C D
  • B A C D
  • C A C D D
  • D A B D
  • E A B D C
Explanation

Java Strings are immutable, so every String method that appears to modify a string, including replace(), actually returns a new String object rather than mutating the original in place. Because the statement ta.replace('C', 'D') never reassigns its result back to ta, that call has no observable effect whatsoever on ta's contents. After ta = ta.concat("B ") and ta = ta.concat(tb), ta holds "A B C "; the discarded replace() call leaves that value untouched, and the final ta = ta.concat(tb) appends "C " once more, so the printed result reads A B C C.

Community Discussion

No comments yet. Be the first to start the discussion!