Although the replace() and replaceAll() replace all occurrences in a string with a given character or string, they serve different purposes and work differently. 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 Java String class.
*Java String.replace() method: *
The replace() method is part of the Java String class introduced in SDK 1.5. 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
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
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: *
The method replaceAll()replaces each substring matching the given regex with the replacement.
Signature:
public replaceAll(String regex, String replacement)
Example:
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
Starting from Java 9+, the replace() 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.
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.
.
Top comments (0)