Homeβ€Ί Javaβ€Ί Java String replace(), replaceAll() and replaceFirst()

Java String replace(), replaceAll() and replaceFirst()

Where developers are forged. Β· Structured learning Β· Free forever.
πŸ“ Part of: Strings β†’ Topic 15 of 15
Understand the difference between Java String replace(), replaceAll(), and replaceFirst().
πŸ§‘β€πŸ’» Beginner-friendly β€” no prior Java experience needed
In this tutorial, you'll learn:
  • replace() uses literal strings (no regex) and replaces all occurrences. Use it when you want literal substitution.
  • replaceAll() uses regex for the first argument. Special regex characters (., |, +, *, ?) must be escaped with \\ when you want them treated literally.
  • replaceFirst() replaces only the first regex match β€” useful for log prefix replacement or structured string editing.
✦ Plain-English analogy ✦ Real code with output ✦ Interview questions
⚑ Quick Answer
Java gives you three replace methods and the names are slightly misleading. replace() sounds like it replaces one thing β€” but it replaces all occurrences too, just without regex. replaceAll() sounds like 'replace all' but the key difference is it uses a regex pattern. Knowing which one to reach for comes down to: do I need regex power, or am I just doing a literal substitution?

replace() vs replaceAll() is a genuine source of bugs. Both replace all occurrences. The difference is the first argument: replace() treats it as a literal string; replaceAll() treats it as a regex. Passing a string like '.' to replaceAll() when you mean a literal dot will produce very surprising results.

replace(), replaceAll(), and replaceFirst() with Examples

StringReplaceExample.java Β· JAVA
1234567891011121314151617181920212223242526272829303132333435363738394041424344
package io.thecodeforge.strings;

public class StringReplaceExample {

    public static void main(String[] args) {
        String url = "https://thecodeforge.io/payment/service/docs";

        // replace(char, char) β€” single character replacement
        String noSlashes = url.replace('/', '-');
        System.out.println(noSlashes);
        // https:--thecodeforge.io-payment-service-docs

        // replace(String, String) β€” literal string, all occurrences
        String http = url.replace("https", "http");
        System.out.println(http);
        // http://thecodeforge.io/payment/service/docs

        // replaceAll(regex, replacement) β€” regex-powered, all occurrences
        String camelCase = "paymentRetryService";
        // Insert underscore before each uppercase letter
        String snakeCase = camelCase.replaceAll("([A-Z])", "_$1").toLowerCase();
        System.out.println(snakeCase); // payment_retry_service

        // replaceAll with DOT β€” common bug
        String dotted = "192.168.1.1";
        System.out.println(dotted.replaceAll(".", "X"));   // XXXXXXXXXX β€” dot = any char!
        System.out.println(dotted.replaceAll("\\.", "X")); // 192X168X1X1 β€” escaped dot
        System.out.println(dotted.replace(".", "X"));      // 192X168X1X1 β€” safer for literal

        // replaceFirst() β€” only the first match
        String log = "ERROR:101 ERROR:102 ERROR:103";
        System.out.println(log.replaceFirst("ERROR", "WARN"));
        // WARN:101 ERROR:102 ERROR:103

        // replaceAll for removing whitespace
        String messy = "  payment   service  ";  
        String clean = messy.replaceAll("\\s+", " ").trim();
        System.out.println(clean); // payment service

        // Replacing special regex chars in replacement string: use \\$ for literal $
        String price = "Amount: $100";
        System.out.println(price.replaceAll("\\$", "USD ")); // Amount: USD 100
    }
}
β–Ά Output
https:--thecodeforge.io-payment-service-docs
http://thecodeforge.io/payment/service/docs
payment_retry_service
XXXXXXXXXX
192X168X1X1
192X168X1X1
WARN:101 ERROR:102 ERROR:103
payment service
Amount: USD 100
MethodFirst Arg TypeReplacesRegex?
replace(char, char)Literal charAll occurrencesNo
replace(String, String)Literal stringAll occurrencesNo
replaceAll(regex, str)Regex patternAll matchesYes
replaceFirst(regex, str)Regex patternFirst match onlyYes

🎯 Key Takeaways

  • replace() uses literal strings (no regex) and replaces all occurrences. Use it when you want literal substitution.
  • replaceAll() uses regex for the first argument. Special regex characters (., |, +, *, ?) must be escaped with \\ when you want them treated literally.
  • replaceFirst() replaces only the first regex match β€” useful for log prefix replacement or structured string editing.
  • When in doubt between replace() and replaceAll() for literal substitution, prefer replace() β€” it's safer and avoids unintended regex interpretation.

⚠ Common Mistakes to Avoid

  • βœ•Using replaceAll(".", "X") to replace dots β€” dot in regex matches any character. Use replace(".", "X") for literal dot replacement, or replaceAll("\\.", "X").
  • βœ•Using replaceAll("|", ...) for pipe characters β€” pipe is regex OR. Use replace("|", ...) or replaceAll("\\|", ...).
  • βœ•Forgetting that replace() (not replaceAll()) also replaces ALL occurrences β€” the method name doesn't say 'all' but it does replace every match.

Interview Questions on This Topic

  • QWhat is the difference between String.replace() and String.replaceAll() in Java?
  • QWhat does 'hello.world'.replaceAll('.', 'X') return, and why?

Frequently Asked Questions

What is the difference between Java String replace() and replaceAll()?

Both replace all occurrences. The difference is the first argument: replace() treats it as a literal character or string. replaceAll() treats it as a regular expression. Use replace() for simple literal substitutions. Use replaceAll() when you need regex power, but remember to escape special regex characters.

Why does replaceAll('.', 'X') replace every character in Java?

The dot in a regular expression means 'match any character'. replaceAll('.', 'X') matches every single character in the string and replaces each with X. To replace a literal dot, either use replace('.', 'X') or replaceAll('\\.', 'X').

πŸ”₯
Naren Founder & Author

Developer and founder of TheCodeForge. I built this site because I was tired of tutorials that explain what to type without explaining why it works. Every article here is written to make concepts actually click.

← PreviousJava Split String: By Delimiter, Regex and Limit
Forged with πŸ”₯ at TheCodeForge.io β€” Where Developers Are Forged