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




