Java String replace FAQ: Why isn't my Java String replace / replaceAll / replaceFirst code working?
The Java String class has several methods that usually make it really easy to replace one text pattern with another. I say "usually" because what occassionally happens is that I forget that a Java String is immutable (it can't be changed), so I accidentally try some String replace
, replaceAll
, or replaceFirst
code that looks like this:
// (string replaceall error; you can't modify a java string) currentString.replaceAll("<", "<");
and then after running this code and printing out my currentString, I wonder why the String replaceAll
method isn't working.
The solution
Of course the String replaceAll
method is working, I'm just not using it properly. To use it properly, I need to remember that you can't change a Java String, but you can assign the result of the String replaceAll method to a String reference, like this:
// the correct string replaceall use currentString = currentString.replaceAll("<", "<");
Hopefully the difference in those two examples is apparent. In the first example I'm calling the replaceAll
method on my String object, hoping that my current String object will somehow be changed. (It won't be changed; Strings are immutable, I just sometimes forget this, lol.)
In the second example I'm doing the correct thing, calling the replaceAll
method on my currentString
object, then assigning that result back to my currentString
reference.
Technically the new currentString
reference is pointing to a new String object in memory, but the important thing is that this is the correct way to use the replace
, replaceAll
, and replaceFirst
methods -- assign the result to a new String reference, then use that reference.