-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?

1
  • String.replaceAll() returns a new instance of String with the changes. The original String is not changed because String is immutable. Commented Feb 10, 2016 at 12:23

2 Answers 2

4

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

myString = myString.replaceAll( "old", "new" );
Sign up to request clarification or add additional context in comments.

1 Comment

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.
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.