liveBook · Manning

Replace method

As explained in 100 Java Mistakes and How to Avoid Them

The Java String.replace method returns a string in which matching occurrences of a target character or sequence are replaced with a specified replacement character or sequence.

Java String.replace returns a string with every matching occurrence of a literal character or character sequence replaced; unlike replaceAll(), it does not interpret the target as a regular expression. section 6.11 section 6.6

String template =  
  "<html>\n" + 
  "  <head><title>Welcome</title></head>\n" + 
  "  <body>\n" + 
  "    <h1>Hello, $user$!</h1>\n" + 
  "    <hr>\n" + 
  "    <p>Welcome to our web-site</p>\n" + 
  "  </body>\n" + 
  "</html>\n";

A concatenated multiline template containing a placeholder illustrates the expression structure that makes a replace call easy to misapply. section 2.4

A replacement applied to the wrong string segment

In `String greetingPage = "<html>\n" + ... + "</html>\n".replace("$user$", userName);`, replace() receives only the final `"</html>\n"` segment. The call therefore has no effect, leaving `$user$` visible without causing a compilation error or runtime exception. Parenthesize the complete concatenation or extract it first: `String greetingPage = template.replace("$user$", userName);`. section 2.4

String greetingPage = """
        <html>
          <head><title>Welcome</title></head>
          <body>
            <h1>Hello, $user$!</h1>
            <hr>
            <p>Welcome to our web-site</p>
          </body>
        </html>
        """.replace("$user$", userName);

A Java 15-or-newer text block keeps the complete template together before applying replace(), avoiding the concatenation mistake. section 2.4

Use replace() deliberately:

  • Choose replace() for literal substring replacement; choose replaceAll() only when a regular expression is intended, and choose replaceFirst() when only the first match should change. section 6.11 section 6.6
  • Prefer replace() when search text or replacement text can come from users: replaceAll() treats the search as a pattern and gives replacement strings special meaning to sequences such as $0 and $1. section 6.6
  • Parenthesize complex qualifiers, extract them into variables, and consider text blocks for multiline templates; IntelliJ IDEA may detect replacements that have no effect. section 2.4

Why replaceAll() is unsafe for a literal template

With `template.replaceAll("USER_NAME", user)`, a username such as `$0ccerman` can become `USER_NAMEccerman`, while `$1lverG1rl` can cause an IndexOutOfBoundsException. `template.replace("USER_NAME", user)` performs the intended literal substitution. section 6.6

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains literal matching, replacement scope, precedence failures, regex hazards, and static-analysis assistance through focused examples.
Examples
Uses multiline HTML templates, user placeholders, literal usernames, and regex replacement-group failures.
What it assumes
Assumes familiarity with Java method calls, string concatenation, and basic regular-expression terminology.
What you can do after
Diagnose ineffective replacements and select replace(), replaceAll(), or replaceFirst() according to matching and replacement requirements.
How it connects
Connects replace() with replaceAll(), replaceFirst(), regular expressions, string concatenation, text blocks, and static analysis.

Also explained in

Compare how 5 books explain replace method →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.