The String.replace() method returns a new string resulting from replacing all occurrences of a specified character or literal substring with a replacement sequence.
Literal Matching & Immutability: Unlike replaceAll() which interprets search patterns as regular expressions, replace() performs literal string matching without regex overhead. Because Java strings are immutable, it never alters the original instance. For single regex substitutions, explore replaceFirst(), or slice text with substring().
Java defines two overloads in java.lang.String to support both primitive character and literal sequence replacement:
// 2 Overloaded signatures of replace() in java.lang.String
public String replace(char oldChar, char newChar)
public String replace(CharSequence target, CharSequence replacement)
| Signature | Target & Replacement Type | Matching Mechanics |
|---|---|---|
replace(char oldChar, char newChar) |
Primitive char |
Replaces every occurrence of oldChar with newChar in-place. |
replace(CharSequence target, CharSequence replacement) |
CharSequence (String, StringBuilder) |
Replaces every occurrence of literal target with replacement. |
When replacing single characters, the char overload operates rapidly across the character sequence:
String str = "Welcome to plus2net.com";
// Replace all occurrences of char 'o' with '*'
String result = str.replace('o', '*');
System.out.println(result); // Welc*me t* plus2net.c*mTerminal Output:
Welc*me t* plus2net.c*m
The CharSequence overload substitutes every occurrence of multi-character tokens without compiling regex patterns:
String str = "Welcome to plus2net.com";
// Replace all occurrences of literal substring "com" with "net"
String result = str.replace("com", "net");
System.out.println(result); // Welnete to plus2net.netTerminal Output:
Welnete to plus2net.net
Because strings in Java are strictly immutable, calling replace() does not modify the source object. You must capture or reassign the result:
String original = "Java 8";
// WRONG: Ignoring the return value (original string is NEVER modified)
original.replace("8", "21");
System.out.println("Uncaptured: " + original); // Java 8
// CORRECT: Reassign or capture the new String instance
original = original.replace("8", "21");
System.out.println("Captured: " + original); // Java 21Terminal Output:
Uncaptured: Java 8
Captured: Java 21
The difference between literal string matching and regular expression evaluation is critical in Java:
| Method | Pattern Interpretation | Scope of Replacement |
|---|---|---|
str.replace(target, replacement) |
Literal text (never regex). | Replaces all occurrences across the string. |
str.replaceAll(regex, replacement) |
Regular expression pattern. | Replaces all regex matches. |
str.replaceFirst(regex, replacement) |
Regular expression pattern. | Replaces only the first regex match. |
String text = "192.168.1.1";
// 1. replace(): Treats "." as a LITERAL period dot
String cleanIp = text.replace(".", "-");
System.out.println("replace('.'): " + cleanIp); // 192-168-1-1
// 2. replaceAll(): Treats "." as REGEX (matches EVERY character!)
String ruinedIp = text.replaceAll(".", "-");
System.out.println("replaceAll('.'): " + ruinedIp); // -----------Terminal Output:
replace('.'): 192-168-1-1
replaceAll('.'): -----------
Passing null as either the search target or the replacement throws a NullPointerException. Guard against crashes with null checks:
String data = "user_name_2026";
String target = null;
// RISKY: Passing null raises NullPointerException
try {
System.out.println(data.replace(target, "guest"));
} catch (NullPointerException e) {
System.out.println("Caught NullPointerException on null target!");
}
// SAFE APPROACH: Verify inputs are non-null
String rep = (target != null) ? data.replace(target, "guest") : data;
System.out.println("Safe result: " + rep);Terminal Output:
Caught NullPointerException on null target!
Safe result: user_name_2026
Because replace() returns a new String, calls can be chained fluently to populate dynamic message templates:
String template = "Hello {name}, your confirmation code is {code}.";
String message = template.replace("{name}", "Sarah")
.replace("{code}", "XYZ-789");
System.out.println(message);Terminal Output:
Hello Sarah, your confirmation code is XYZ-789.
Converting Windows file system paths into standard Unix/web path formats:
String windowsPath = "C:\\Users\\Admin\\Documents\\Report.pdf";
// Normalize Windows backslashes into standard web forward slashes
String unixPath = windowsPath.replace('\\', '/');
System.out.println(unixPath);Terminal Output:
C:/Users/Admin/Documents/Report.pdf
In "Welcome to plus2net.com".replace("com", "net"), the letters "com" inside "Welcome" are also replaced, producing "Welnete to plus2net.net". Use whole-word regex or delimiters when targeting standalone tokens.
Calling str.replaceAll(".", "/") replaces every character in the string because . is the regex wildcard for any character. Always use str.replace(".", "/") when searching for literal dots.
You can compile and run this complete verification class locally in any Java IDE or environment:
public class StringReplaceFullDemo {
public static void main(String[] args) {
String input = "apple,banana,apple,orange";
// 1. Replace all occurrences of substring
String replaced = input.replace("apple", "mango");
if (replaced.equals("mango,banana,mango,orange")) {
System.out.println("Check 1 Passed: Literal word replacement verified.");
}
// 2. Replace characters
String dashed = input.replace(',', '-');
if (dashed.equals("apple-banana-apple-orange")) {
System.out.println("Check 2 Passed: Character substitution verified.");
}
// 3. Unmatched target returns exact same string instance
String unchanged = input.replace("grape", "pear");
if (unchanged == input) {
System.out.println("Check 3 Passed: Unmatched replacement returns same instance.");
}
System.out.println("All String.replace() unit tests passed successfully!");
}
}Terminal Output:
Check 1 Passed: Literal word replacement verified.
Check 2 Passed: Character substitution verified.
Check 3 Passed: Unmatched replacement returns same instance.
All String.replace() unit tests passed successfully!
No. If the target character or sequence is not found in the string, Java optimizes by returning the exact same string reference (this) without allocating a new object.
Both replace all occurrences. However, replace() treats search strings as literal text, while replaceAll() interprets them as regular expressions.
Yes. If target is "", Java inserts the replacement string between every character and at the start and end of the string.
Use replaceFirst(regex, replacement) or combine indexOf() with substring().
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.