replace() vs replaceAll() in Java
Fast recall
Quick revision
Core answer
replace(CharSequence target, CharSequence replacement) treats the target literally. replaceAll(String regex, String replacement) treats the first argument as a regular expression, and $ and backslash have special meaning in the replacement string. Prefer replace for fixed text; when replacement text is literal with replaceAll, use Matcher.quoteReplacement.Whether you know the regex vs literal distinction between these two methods.
Using replaceAll() for literal replacements — if the 'old' string contains regex metacharacters like . or + it will match more than expected. replace() is always safer for literal text.
Mention replaceFirst(regex, replacement) which replaces only the first match. Also: in replaceAll() the replacement string itself has special meaning for $1, $2 (captured groups) and \, so literal backslashes and dollar signs need escaping there too.
Interview-ready guide
Interview answer
Both replace text and both replace every occurrence — the name replaceAll is a little misleading there, because replace() also replaces all of them. The real difference is how each reads its first argument. replace() takes a literal string where every character is matched exactly; replaceAll() takes a regular expression.
That distinction bites when your search text contains regex metacharacters. The textbook example is "a.b.c".replaceAll(".", "-") — you expect the dots gone, but . in regex matches any character, so you get a row of dashes. With replace(".", "-") it does exactly what you meant. So my default is replace() for fixed text, and I only switch to replaceAll() when I genuinely need a pattern — collapsing runs of whitespace with "\\s+", or stripping digits with "\\d+".
One subtlety worth mentioning: in replaceAll() the replacement string is special too — $1 pulls in a captured group and backslash escapes, so to insert a literal dollar sign you need Matcher.quoteReplacement(). And if you only want the first hit, that's replaceFirst(). Bottom line: literal text, use replace(); reach for replaceAll() only when you actually want regex.
replace() vs replaceAll() in Java
Direct Answer
replace(CharSequence target, CharSequence replacement) treats the target literally. replaceAll(String regex, String replacement) treats the first argument as a regular expression, and $ and backslash have special meaning in the replacement string. Prefer replace for fixed text; when replacement text is literal with replaceAll, use Matcher.quoteReplacement.
Code Example
public class ReplaceDemo {
public static void main(String[] args) {
String s = "a.b.c.d";
// replace() — treats '.' as literal dot
System.out.println(s.replace(".", "-")); // a-b-c-d
// replaceAll() — '.' is regex metachar = any character
System.out.println(s.replaceAll(".", "-")); // ------- (replaces every char!)
// replaceAll() correct use — escape the dot
System.out.println(s.replaceAll("\\.", "-")); // a-b-c-d
// replaceAll() genuine use case — collapse multiple spaces
String messy = "Hello World !";
System.out.println(messy.replaceAll("\\s+", " ")); // Hello World !
// replaceAll() — remove all digits
String code = "abc123def456";
System.out.println(code.replaceAll("\\d+", "")); // abcdef
// replaceFirst() — only the first match
System.out.println("aabbcc".replaceFirst("b", "X")); // aaXbcc
}
}
Common Mistakes & Pitfalls
- Using
replaceAll()for literal text — if the target holds.,+,|, or(, it matches far more than intended.replace()is the safe literal choice and needs no escaping. - The dot trap —
replaceAll(".", "-")replaces every character, not the dots. You meantreplace(".", "-"), orreplaceAll("\\.", "-")if you specifically need regex. - Forgetting the replacement string is special too —
$and\in the second argument ofreplaceAll()mean group references and escapes; inserting a literal$5needsMatcher.quoteReplacement(). - Thinking
replace()only swaps the first match — it replaces all occurrences, exactly likereplaceAll(). The name difference is regex vs literal, not quantity;replaceFirst()is the one that stops at one. - Recompiling a regex every call — repeatedly calling
replaceAll()in a loop recompiles the pattern each time; precompile withPattern.compile()and reuse theMatcher.
Check your understanding
Answer these without looking back at the article.
- How does String.replaceAll() handle regex groups like $1 in the replacement?
- How would you remove all non-alphanumeric characters from a String in Java?
- What is Pattern and Matcher in Java and when do you use them?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.