STRING INSTANCE METHODS
Java String replace() method
replace() replaces every occurrence of a specified character or text sequence and returns a String value. The original text stays unchanged. The method uses literal matching rather than a regular expression.
Replacing a character in a string
String tekstas = "Hello World";
String rezultatas = tekstas.replace('o', 'p');
System.out.println(rezultatas);Hellp Wprld
- The variable
tekstasstores the sentence Hello World. - The first argument
'o'specifies the character to replace. - The second argument
'p'specifies the new character. - Both o characters are replaced, producing Hellp Wprld.
Why is replace() an instance method?
replace() is called on a specific string: it searches that string for the character or sequence to replace. The arguments specify what to replace and what to use instead.
String rezultatas = tekstas.replace('o', 'p');
We do not write String.replace(...), because this method is not static. The receiver is the value on the left of the dot: tekstas.
Method syntax
public String replace(char oldChar, char newChar)
public String replace(CharSequence target, CharSequence replacement)
| Part | Meaning |
|---|---|
oldChar | The char character to replace. |
newChar | The replacement char character. |
target | The target CharSequence, for example a String value. |
replacement | The replacement CharSequence. It can be shorter or longer than the target. |
| Return type | String – The returned text with the replacements applied. |
Single quotes, such as 'a', denote one char value. Double quotes, such as "Java", denote a String value. Use the second overload to replace a sequence of characters.
The overload with CharSequence is available since Java 5. Ordinary strings can be supplied as both arguments; no extra objects are needed just to satisfy the parameter type.
Replacing a text sequence
String tekstas = "Java Quest, Java lessons";
String rezultatas = tekstas.replace("Java", "Kotlin");
System.out.println(rezultatas);Kotlin Quest, Kotlin lessons
Both occurrences of Java are replaced. The replacement Kotlin is longer, so the total result length can change. The method does not stop after the first match.
replace() does not check word boundaries. The target can be part of a longer word: "JavaScript".replace("Java", "Type") returns TypeScript.
replace() does not change the original string
String tekstas = "Java";
tekstas.replace('J', 'K');
System.out.println(tekstas);
tekstas = tekstas.replace('J', 'K');
System.out.println(tekstas);Java
Kava
String is immutable. The first result is not saved, so the output is still Java. The second result is assigned to the variable, producing Kava.
Uppercase and lowercase letters differ
String tekstas = "Java java JAVA";
System.out.println(tekstas.replace("Java", "Kotlin"));Kotlin java JAVA
Only Java matches. The sequences java and JAVA stay unchanged because their case differs. The method has no separate parameter for ignoring case.
When there is no match or the characters are equal
String tekstas = "abc";
System.out.println(tekstas.replace('x', 'y'));
System.out.println(tekstas.replace('a', 'a'));abc
abc
If the target character is absent, the text content stays the same. Replacing a character with itself also leaves the visible result unchanged. Neither case is an error.
Practical example: adjusting a file name
String failas = "Java Quest Notes.txt";
String rezultatas = failas.replace(' ', '_')
.replace(".txt", ".md");
System.out.println(rezultatas);Java_Quest_Notes.md
- The first
replace()replaces spaces with underscores. - The second
replace()replaces the sequence .txt with .md. - The calls can be chained because each returns a
Stringvalue.
This example changes only the variable’s value; it does not rename a file on disk. The method would also replace .txt inside the name, so a general extension change needs a separate check of the end of the name.
Removing a text sequence
String kodas = "JA-VA-QUEST";
String rezultatas = kodas.replace("-", "");
System.out.println(rezultatas);JAVAQUEST
An empty replacement string "" removes every occurrence of -. Empty single quotes '' are not a valid Java character: use the string overload for removal.
replace() does not interpret regex symbols
String tekstas = "a.b.c";
System.out.println(tekstas.replace(".", "-"));
System.out.println(tekstas.replaceAll(".", "-"));
System.out.println("price".replace("price", "$5"));a-b-c
-----
$5
replace(".", "-")replaces only literal dots.replaceAll(".", "-")uses a regex, where the dot matches every character in this string.- The third call replaces the entire string price with $5.
How does the third call work?
System.out.println("price".replace("price", "$5"));
- The first
"price"is the original string on which the method is called. It is a string literal, rather than a variable name. - Inside the parentheses, the first argument
"price"specifies the target sequence. It matches the entire original string, so the whole word is replaced. - The second argument
"$5"is the replacement text, made of two characters: a dollar sign and the digit 5. The quotes mark the beginning and end of the string in Java code; they are not part of its content. replace()returns the string $5, and the outer call toSystem.out.println(...)prints it. The console shows both characters without quotes.
The dollar sign is intentional: replace() copies it as an ordinary text character. This call does not calculate a price or look for a fifth regex group. In replacement text used by regex replacement methods, a dollar sign can have a special meaning, but no extra escaping is needed here.
Therefore, replace() is suitable for literal text replacement when regex rules and special replacement syntax are unnecessary.
Differences between replace(), replaceAll(), and replaceFirst()
String tekstas = "Java Java";
System.out.println(tekstas.replace("Java", "Kotlin"));
System.out.println(tekstas.replaceAll("Java", "Kotlin"));
System.out.println(tekstas.replaceFirst("Java", "Kotlin"));Kotlin Kotlin
Kotlin Kotlin
Kotlin Java
| Method | What does it replace? |
|---|---|
replace() | All literal matches of a character or text sequence. |
replaceAll() | All matches of a regular expression. |
replaceFirst() | Only the first match of a regular expression. |
In this example, the word Java contains no special regex symbols, so the first two calls produce the same result. This does not mean the methods always behave identically.
Matches are replaced from left to right
System.out.println("aaa".replace("aa", "b"));
System.out.println("a".replace("a", "aa"));ba
aa
In the first call, the first two a characters form the match aa and are replaced by b. The final character remains, producing ba. Characters already consumed by a match are not reused for another match.
In the second call, newly inserted text is not replaced again. The result is aa, rather than endless repetition.
Empty strings and an empty target
System.out.println("[" + "".replace("a", "b") + "]");
System.out.println("ab".replace("", "-"));
System.out.println("[" + "".replace("", "-") + "]");[]
-a-b-
[-]
Searching for a nonempty target in an empty string changes nothing. When the target is "", the replacement is inserted at the beginning, between UTF-16 char units, and at the end.
Thus ab becomes -a-b-, while an empty string receives one -. An empty target is not an error, but its behavior differs from searching for a nonempty sequence.
The target cannot be null
String tekstas = "Java";
String ieskoma = null;
System.out.println(tekstas.replace(ieskoma, "Kotlin"));NullPointerException
When the target sequence is null, the call throws NullPointerException. Java has no sequence to search for. This differs from an empty string "".
The replacement cannot be null
String tekstas = "Java";
String naujas = null;
System.out.println(tekstas.replace("Java", naujas));NullPointerException
The replacement sequence cannot be null either. To remove matching text, pass "" rather than null.
The receiver cannot be null
String tekstas = null;
System.out.println(tekstas.replace('a', 'b'));NullPointerException
A null reference cannot receive an instance method call. The char arguments themselves are primitive values and cannot be null. If input may be missing, check the references before calling the method.
Common mistakes
- Expecting
replace()to modify the original string while leaving the result unassigned. - Assuming only the first match is replaced.
- Confusing literal
replace()with methods that use regex. - Forgetting that replacement is case-sensitive.
- Expecting the target to match only whole words or expecting both overlapping matches to be replaced.
When should you use replace()?
Use replace() to replace a specific character or literal sequence throughout a string: change spaces to underscores, remove separators, or replace a repeated name. For regex patterns, use replaceAll(); for only the first regex match, use replaceFirst().