In this section, we will learn what the String replaceAll() method is and how to use it in Java.
What is Java String replaceAll() Method?
When we want to search in a string to find a substring and replace that substring with a new one, then `replaceAll()` method is the way to go.
Note: this method replaces all the occurrences of the substring that we’re looking for in the target string.
Java replaceAll() Method Syntax:
public String replaceAll(String regex, String replacement)
replaceAll() Method Parameters:
- The first argument of the method is a regular expression that defines the substring that we’re looking for in the target string object.
Note: Other than regular expression, the first argument can also be a simple string word or sentence or even a letter. The point is the first argument is considered as the substring that the method should search for in the target string.
- The second argument is the substring that we want to be used as the replacement with the one that might be found in the target string.
Note: Please check the Regular Expression section if you don’t know what it is and how it works.
replaceAll() Method Return Value:
The return value of this method is a new string value that contains the replaced substring.
Note: using this method won’t change the original string value.
replaceAll() Method Exceptions:
The method does not throw an exception.
Example: using String replaceAll() method
public class Simple { public static void main(String[] args) { String w = "@@Life is amazing! @@"; String res = w.replaceAll("@@","**"); System.out.println(res); } }
Output:
**Life is amazing! **