-4

In core java API I studied the method replace(char oldChar,char newChar) in String class and it says that it will replace the oldChar with newChar in the string in each occurrence, buy this explanation output of this program given below should be

A B D C

But the real output is

A B C C

Can anyone explain me why this is happening so.

class A{
    public static void main(String[] args){
        String ta = "A ";
        ta = ta.concat("B ");
        String tb = "C ";
        ta = ta.concat(tb);
        ta.replace('C','D');
        ta = ta.concat(tb);
        System.out.println(ta);
    }
}
user3378165
  • 6,546
  • 17
  • 62
  • 101

1 Answers1

0
 ta.replace('C','D');

This line doesn't change ta. It returns a new string with that change made. You want

ta = ta.replace('C','D');
Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413