Examples
Below are certain examples which depicts the use of replaceAll() function:
- Replacing Characters: Below is an example of replacing every occurrence of a single character.
FileName: Example1.java
Java
public class Example1{
public static void main(String args[]){
String s1="First example for replaceAll() function";
String replaceString=s1.replaceAll("e","a");
//Above function will replace all the occurrences of "e" to "a"
System.out.println(replaceString);
}}

You can also try this code with Online Java Compiler
Run Code
Output:
First axampla for raplacaAll() function
- Replacing Words: Below is an example of replacing every word, or every set of words.
FileName: Example2.java
Java
public class Example2{
public static void main(String args[]){
String s1="Today is a holiday. Ram is watching TV.";
String replaceString=s1.replaceAll("is","was");//replaces all occurrences of "is" to "was"
System.out.println(replaceString);
}}

You can also try this code with Online Java Compiler
Run Code
Output:
Today was a holiday. Ram was watching TV.
- Removing white spaces: Below is an example of removing white spaces from a given sentence using replaceAll() function.
FileName: Example3.java
Java
public class ReplaceAllExample3{
public static void main(String args[]){
String s1="Remove white spaces from the sentence.";
String replaceString=s1.replaceAll("\\s","");
System.out.println(replaceString);
}}

You can also try this code with Online Java Compiler
Run Code
Output:
Removewhitespacesfromthesentence.
- Inserting white spaces: Below is an example of Inserting white spaces in a given sentence using replaceAll() function.
FileName: Example4.java
Java
public class Example4{
public static void main(String argvs[]){
String input_ = "Sentence";
System.out.println(input_);
String regexp = "";
// Inserting white space before and after every character in the given input sentence.
input_ = input_.replaceAll(regexp, " ");
System.out.println(input_); }
}

You can also try this code with Online Java Compiler
Run Code
Output:
Sentence
S e n t e n c e
- PatternSyntaxException: Below we see how replaceAll() function returns PatternSyntaxException when passed with incorrect regular expression.
FileName: Example5.java
Java
public class Example5{
public static void main(String argvs[]){
String str = "Below we see an exception.";
System.out.println(str);
String regex = "\\"; // Incorrect regexp (Regular expression) being passed.
// Calling replaceAll() function now raises PatternSyntaxException.
str = str.replaceAll(regex, "JavaTpoint ");
System.out.println(str); }
}

You can also try this code with Online Java Compiler
Run Code
Output:
Exception in thread "main" java.util.regex.PatternSyntaxException: Unexpected internal error near index 1
\
at java.util.regex.Pattern.error(Pattern.java:1957)
at java.util.regex.Pattern.compile(Pattern.java:1704)
at java.util.regex.Pattern.(Pattern.java:1351)
at java.util.regex.Pattern.compile(Pattern.java:1028)
at java.lang.String.replaceAll(String.java:2223)
at Example4.main(Example4.java:15)
Below we see an exception.
String replace() Method in Java
The replace() method in Java is used to replace all occurrences of a specific character or substring in a string with another character or substring. It creates a new string since strings in Java are immutable.
1. Method Variants:
The replace() method has two main variants:
- replace(char oldChar, char newChar): Replaces all occurrences of a character with another character.
- replace(CharSequence target, CharSequence replacement): Replaces all occurrences of a substring with another substring.
2. Immutable Strings:
The method doesn’t modify the original string but creates a new string with the replacements.
3. Case Sensitivity:
The replace() method is case-sensitive. For example, replacing 'a' will not affect 'A'.
4. NullPointerException Risk:
If the original string or any parameter (e.g., target) is null, the method will throw a NullPointerException.
5. Use Cases:
- Correcting typos in a string.
- Masking or replacing sensitive information (e.g., replacing digits in credit card numbers with *).
- Formatting strings.
Examples
Replacing Characters:
public class ReplaceExample {
public static void main(String[] args) {
String str = "hello world";
String result = str.replace('o', 'a'); // Replace 'o' with 'a'
System.out.println(result); // Output: hella warld
}
}
Replacing Substrings:
public class ReplaceExample {
public static void main(String[] args) {
String str = "I like apples. Apples are sweet.";
String result = str.replace("apples", "bananas"); // Replace "apples" with "bananas"
System.out.println(result); // Output: I like bananas. Apples are sweet.
}
}
Case Sensitivity Demonstration:
public class ReplaceExample {
public static void main(String[] args) {
String str = "Java is Fun. JAVA is Powerful.";
String result = str.replace("JAVA", "Python"); // Case-sensitive
System.out.println(result); // Output: Java is Fun. Python is Powerful.
}
}
Replacing Digits (Masking):
public class ReplaceExample {
public static void main(String[] args) {
String cardNumber = "1234-5678-9876-5432";
String masked = cardNumber.replace("5678", "****");
System.out.println(masked); // Output: 1234-****-9876-5432
}
}
Frequently Asked Questions
How to use String replace() in Java?
Use replace() to replace characters or substrings in a string, e.g., str.replace('a', 'b') or str.replace("old", "new").
How to use replaceAll()?
Use replaceAll() to replace substrings matching a regular expression, e.g., str.replaceAll("\\d", "*") replaces all digits with *.
How to replace string parts in Java?
Use replace() or replaceAll() to replace specific parts of a string. For case-insensitive replacement, combine with Pattern and Matcher.
Conclusion
This article discussed the replaceAll() function offered by the String class in Java. We saw the signature of the function, along with its details, including parameters, exceptions thrown, etc. Further, we saw certain examples, which included replacing characters and words, and inserting and removing spaces using replaceAll() function. If you’d like to know more about Java, Check out our Java-Full stack course.
Once you are done with this, you may check out our Interview Preparation Course to level up your programming journey and get placed at your dream company. Refer to our guided paths on Code360 to learn more about DSA, Competitive Programming, System Design, Javascript, etc. Enrol in our courses, refer to the mock test and problems available, interview puzzles, and look at the interview bundle and interview experiences for placement preparations. We hope that this blog has helped you increase your knowledge regarding such DSA problems, and if you liked this blog, check other links.