-3

I have used below string operation but not able to understand why 1st case is not working.

Case - 1 :

String myString = new String("old String");
System.out.println(myString);
myString.replaceAll( "old", "new" );
System.out.println( myString );

//Output
old String
old String

Case - 2 :

String myString = new String("old String" );
System.out.println(myString);
myString = new String("new String");
System.out.println(myString);

//Output
old String
new String

Why case - 1 is working but case - 2 is not working?

Shiladittya Chakraborty
  • 4,270
  • 8
  • 45
  • 94
  • String.replaceAll() returns a new instance of String with the changes. The original String is not changed because String is immutable. – NickJ Feb 10 '16 at 12:23

2 Answers2

4

String.replaceAll() returns a new string with the specified replacement. You need to do:

myString = myString.replaceAll( "old", "new" );
shmosel
  • 49,289
  • 6
  • 73
  • 138
  • Because this question has been answered so many times before, answering it again only to gain easy reputation is not cool. Especially that the answer is not that great: missing link to documentation for example. – Tunaki Feb 10 '16 at 09:39
0

replaceAll method returns a String object. You must assign this back to myString or to another variable as strings are immutable.

hazra
  • 400
  • 1
  • 6
  • 15