Let's review why your code doesn't provide what you expect.
You create an instance with "wew".
String str = new String("wew");
Then you replace "w" in "wew" with "61" and print the result "61e61"
System.out.println(str.replaceAll("w", "61")); //61e61
Now, the important part here is that the result of str.replaceAll
is a new instance, so str
is still "wew".
System.out.println(str); // wew
This explain why the second replacement will print "w31w"
System.out.println(str.replaceAll("e", "31")); //w31w
The reason is that String
are immutable, so when you try to change the value of an immutable instance, a new instance is return. So to keep it, you need to assign that instance to a variable.
str = str.replaceAll("w", "61");
Now, the result is kept in the variable "str"
System.out.println(str); // 61e61
Now, one good thing about immutable classes is that method can usually be chained because the return value is an instance of the class itself. So you can call multiple method at one.
str = str.replaceAll("w", "61").replaceAll("e", "31");
System.out.println(str); // 613161
But if you want to print the intermediate result, you will need do it in two statement
str = str.replaceAll("w", "61");
System.out.println(str); // 61e61
System.out.println(str = str.replaceAll("e", "31")); // 613161
Note the last statement, it is possible to merge both assignment and print statement.
First str = ..
will be evaluated then the result will be printed.