Java String replaceAll - why isn’t my “replace” method working?

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("<", "&lt;");

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("<", "&lt;");

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.

Comments

Permalink

Be careful with replace vs replaceAll. replaceAll takes a regular expression. I think in this case it doesn't matter, but sometimes it does.

Also, the tricky thing with the method returning a new string is sometimes useful. You can do things like

String y = x.replace("<", "<")
.replace(">", ">")
.replace("\t", " ");

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.