Mastering Java String Replacement: replace(), replaceAll(), and replaceFirst() Explained
The Java String class offers three powerful replacement methods that let you modify text efficiently: replace(), replaceAll(), and replaceFirst(). Each serves a distinct purpose and is optimized for different use‑cases.
Java String replace()
The replace() method performs a straightforward character or string substitution. It scans the entire string and replaces every occurrence of the target with the replacement, returning a new String instance. This method is ideal when you need a direct, non‑regex substitution.
Syntax
public String replace(CharSequence target, CharSequence replacement)
Parameters
target– The sequence of characters you want to replace.replacement– The sequence that will replacetarget.
Example
public class ReplaceExample {
public static void main(String[] args) {
String original = "the quick fox jumped";
System.out.println("Original: " + original);
System.out.println("After replace(\"fox\", \"dog\"): " + original.replace("fox", "dog"));
System.out.println("After replace('t', 'a'): " + original.replace('t', 'a'));
}
}
Output
Original: the quick fox jumped
After replace("fox", "dog"): the quick dog jumped
After replace('t', 'a'): ahe quick fox jumped
Java String replaceAll()
The replaceAll() method uses a regular expression (regex) to identify matches across the entire string. It then substitutes each match with the specified replacement, returning a new string. This method is perfect when you need pattern‑based replacements.
Signature
public String replaceAll(String regex, String replacement)
Parameters
regex– The regex pattern to locate substrings.replacement– The string that will replace each match.
Example
public class ReplaceAllExample {
public static void main(String[] args) {
String text = "Guru99 is a site providing free tutorials";
String withoutSpaces = text.replaceAll("\\s", "");
System.out.println(withoutSpaces);
}
}
Output
Guru99isasiteprovidingfreetutorials
Java String replaceFirst()
The replaceFirst() method behaves like replaceAll() but only affects the first match found. It scans from the start of the string and stops after the first replacement, making it useful when only a single occurrence should be altered.
Signature
public String replaceFirst(String regex, String replacement)
Parameters
regex– The regex pattern that identifies the target substring.replacement– The string that will replace the first match.
Example
public class ReplaceFirstExample {
public static void main(String[] args) {
String sentence = "This website providing free tutorials";
String updated = sentence.replaceFirst("s", "9");
System.out.println(updated);
}
}
Output
Thi9 website providing free tutorials
Choosing the Right Method
- Use
replace()for simple, non‑regex substitutions. - Choose
replaceAll()when you need to replace every match of a regex pattern. - Opt for
replaceFirst()if only the first occurrence should be changed.
These methods are immutable; they never alter the original string but return a new instance, ensuring thread safety and predictable behavior in concurrent environments.
Java
- Java Methods: How to Define, Call, and Use Them Effectively
- Mastering Java Strings: Creation, Methods, and Best Practices
- Mastering Java Polymorphism: Concepts, Examples, and Best Practices
- Master Java String Manipulation: Essential Functions, Methods, and Practical Examples
- Java String length() Method: How to Get a String’s Size (Example)
- Mastering Java String.indexOf(): Locating Substrings & Practical Examples
- Understanding Java String.charAt(): Syntax, Return Type, Exceptions, and a Practical Example
- Mastering Java’s String.endsWith(): How to Check String Suffixes with Examples
- Java String toLowerCase() & toUpperCase(): Convert Text Case with Locale Awareness
- Mastering Java's split() Method: A Practical Guide with Code Examples