In this Java tutorial, you will learn how to replace all the occurrences of an old string with a replacement string using String.replaceAll() method, with examples.

Java – Replace all Occurrences of a Substring in a String

To replace all the occurrences of an old string with a replacement string, you can use String.replaceAll() method.

In your application, when working on string processing or some cleaning, you may need to replace some or all occurrences of some specific words with new replacements, or you want to completely remove them.

The syntax of String.repalceAll() is given below.

</>
Copy
 public String replaceAll(String regex, String replacement)

For regex, you can provide the old string you would like to replace. You may provide a string constant or some regex, based on your Java application’s requirement.

For replacement, provide the new string you would like to replace with.

Examples

1. Replace all occurrences with a new string

In this example, we shall take three strings: str1, old_string, and new_string. We shall try to replace all the occurrences of the string old_string with new_string in str1.

Example.java

</>
Copy
public class Example { 
    public static void main(String[] args) {
        String str1 = "Hi! Good morning. Have a Good day.";
        String old_string = "Good";
        String new_string = "Very-Good";
        
        //replace all occurrences
        String resultStr = str1.replaceAll(old_string, new_string);
        System.out.println(resultStr);
    }
}

Run the above Java program in console or your favorite IDE, and you shall see an output similar to the following.

Output

Hi! Very-Good morning. Have a Very-Good day.

All the occurrences of old string are replaced with new string.

2. Replace all occurrences with New string – Negative Scenario

In this example, we shall take three strings: str1, old_string, and new_string. We shall try to replace all the occurrences of the string old_string with new_string in str1. But old_string is not present in str1.

Example.java

</>
Copy
public class Example { 
    public static void main(String[] args) {
        String str1 = "Hi! Good morning. Have a Good day.";
        String old_string = "Bad";
        String new_string = "Very-Good";
        
        //replace all occurrences
        String resultStr = str1.replaceAll(old_string, new_string);
        System.out.println(resultStr);
    }
}

Run the above program.

Output

Hi! Good morning. Have a Good day.

Since the old_string is not present in str1, replaceAll() returns str1 unchanged.

Conclusion

In this Java Tutorial, we have learned how to replace the first occurrence of a sub-string with another in a string.