Although the String java class methods replace() and replaceAll() replace occurrences in a string with a given character or string, they serve different purposes and work differently internally. Knowing how both methods work is essential to understand why one option is preferable.
In this article, I will explain the difference between replace vs. replaceAll methods in the Java String class.
Java String.replace() method: Link to heading
The method creates a new String object where specified characters or substrings are replaced with new ones.
Note: Java strings are immutable, meaning they cannot be changed. The replace() method creates a new string.
The method has two signatures:
replace(char oldChar, char newChar)
replace(CharSequence target, CharSequence replacement)
The first method replaces all occurrences of a specified oldChar with a newChar. In contrast, the second replaces all occurrences of a specified target CharSequence with a replacement CharSequence (CharSequence is a superclass of String, meaning it accepts String as an argument).
Example 1 Link to heading
Replace all occurrences of the character ‘o’ with ‘x’.
String originalString = "o1o2o3o4";
String newString = s.replace('o', 'x');
// Original String: -> "o1o2o3o4"
// New String: -> "x1x2x3x4"
Example 2 Link to heading
Replace all occurrences of the string “red” with “black”.
String originalString = "The red car and the red house are both red.";
String newString = originalString.replace("red", "black");
// Original String: The red car and the red house are both red.
// New String: The black car and the black house are both black.
Java String.replaceAll() method: Link to heading
The method replaceAll() replaces each substring matching the given regex with the replacement.
Signature: Link to heading
public replaceAll(String regex, String replacement)
Example: Link to heading
String originalString = "The red car and the red house are both reddish.";
// Replace all substrings matching the regex "red\\w*" with "black"
String newString = originalString.replaceAll("red\\w*", "black");
// Original String: The red car and the red house are both reddish.
// New String: The black car and the black house are both black.
Conclusion Link to heading
Starting from Java 9+, the replace() the method was optimized to remove regex. However, the replaceAll() method still calls the java.util.regex.Pattern.compile()
method every time it is invoked, even if the first argument (regex) is not a regular expression. This leads to a significant overhead.
This it is recommended to use replaceAll() only when the first argument is a real regex; otherwise, use replace(), which does not have the performance drawback of regex.