replace() in Java
Overview
As an end user, many times we need functionality to change one char/string to another char/string. We are used to doing this type of changes in our PowerPoint Presentations, Excel Sheets or Word Documents etc.
Example of replace() in Java

However, these are the examples of end-user applications but behind all these applications, there are some programming logic/methods that are running, which have been implemented by the developers. Today, in this article, we are going to learn about such programming logic/method in Java which is the replace() method. This method is used for replacing one char/substring to another char/substring in the new string object and returns that object.
Syntax of replace() in Java
replace() method in Java has two syntaxes and according to our need, we will use one of the below mentioned syntax.
Syntax for Replacing a Character:
Here, we are replacing one character with another character with the help of the Java replace() method.
Syntax for Replacing a Substring:
Here, we are replacing one string to another string with the help of Java replace() method.
As string is the object of class String and replace() method is a built-in method of Java String class, we do not need to implement this method. We can directly call the replace() method by creating an object of the String class. replace() method takes the original string object as an input parameter and returns the new string object.
Parameters of replace() in Java
To change all the occurrence of one particular character to another character, we will use the first syntax of replace() method.
oldChar - It is the character that we want to change in our string.
newChar - It is the character that we want to use, in the place of oldChar, in our string.
To change all the occurrence of one particular string or substring to another string or substring, we will use the second syntax of the replace() method.
oldString - It is the string or substring that we want to change in our original string.
newString - It is the string or substring that we want to use, in the place of an old string or substring, in our original string.
Return Value of replace() in Java
Whenever we use the replace() method in Java, it returns a new string where each occurrence of char/word/sentence has been replaced with a new char/word/sentence.
If there is no match for our new char/word/sentence, replace() method returns the original string.
Note - If we use one parameter as a character and another as a string or vice versa, the system will throw a compile-time error.
Output
Now, let’s understand replace() method’s syntax with the help of one short example.
Example - Replacing one character to Another in Java Using replace() Method.
Output:
In the above code, we are displaying the string object "G00d M0rning" and then, calling the replace() method with the help of this object. We are replacing '0'(zero) to the 'o'(letter o) and then printing the replaced string on the screen.
Exception of replace() in Java
We can not use null as an argument in the replace() method. If we use null as an argument in the replace() method, system will throw a NullPointerException.
public class Main{
public static void main(String[] arg){
String obj = "Hello World";
try{
obj = obj.replace("World", null); //replacing "World" to null and trying to store it to again 'obj'
System.out.println(obj); //Displaying replaced string
}
catch (NullPointerException e){
System.out.println("NullPointerException occurred!");
}
}
}
Output
More Details About replace() Method in Java
- replace() method is a built-in method. It is define in the Java String class
- It is a case-sensitive method, meaning, it considers ‘A’ and ‘a’ as different characters.
- In the case of string.replace(char oldChar, char newChar), system will change all the occurrences of a given character with a new character.
Example:
- In the case of string.replace(CharSequence oldWord, CharSequence newWord), system will change all the occurrences of a given substring with a new substring.
- This method has been available since Java 1.5.
- In the below example, notice that, program will not change the occurrence of single ‘x’ to single ‘o’ as it specifically matches for double ‘xx’ and change to double ‘oo’.
Example:
"Txday is the gxxd day.".replace("xx", "oo"); will returns “Txday is a good day.”
Let us see some useful examples of the Java string replace() method.
More Examples
Example 1: Replacing Occurrences of One Character to Another Character
public class Main{
public static void main(String[] arg){
String obj = "This is zhe example of replacing occurrences of one characzer zo anozher.";//Original string
System.out.println("Original String - "+obj);//Displaying original string
obj = obj.replace('z', 't');//Using replace() method to do correction in the original string
System.out.println("Corrected String - "+obj);//Displaying corrected string
}
}
Output
Original String - This is zhe example of replacing occurrences of one characzer zo anozher. Corrected String - This is the example of replacing occurrences of one character to another. Given program is matching each occurrence of ‘z’ and then replacing it with ‘t’. After that, it is displaying the replaced string on the screen.
Example 2(a): Replacing Occurrences of One Substring to Another Substring
public class Main{
public static void main(String[] arg){
String obj = "There are two major countries in z North America Region, Canada and z USA.";//Original string
System.out.println("Original String - "+obj);//Displaying original string
obj = obj.replace("z", "the");//Using replace() method to do correction in the original string
System.out.println("Corrected String - "+obj);//Displaying corrected string
}
}
Output
Original String - There are two major countries in z North America Region, Canada and z USA. Corrected String - There are two major countries in the North America Region, Canada and the USA.
Given program is matching each occurrence of ‘z’ and then replacing it with ‘the’. After that, it is displaying the replaced string on the screen.
Example 2(b): Replacing Occurrences of One Substring to Another Substring
public class Main{
public static void main(String[] arg){
String obj = "Life is like riding a bicycle. To keep ur balance, u must keep moving. - Albert Einstein'';//Original string
System.out.println("Original String - "+obj);//Displaying original string
obj = obj.replace("u", "you");//Using replace() method to do correction in the original string
System.out.println("Corrected String - "+obj);//Displaying corrected string
}
}
Output
Original String - Life is like riding a bicycle. To keep ur balance, u must keep moving. - Albert Einstein Corrected String - Life is like riding a bicycle. To keep your balance, you myoust keep moving. - Albert Einstein Given program is matching each occurrence of the ‘u’ and then replacing it with ‘you’. After that, it is displaying the replaced string on the screen.
Now, as we have understood the concept and usage of the replace() method, let’s deep dive into the internal implementation of this built-in method in the String class of Java.
Internal Implementation of replace() Method in Java
1. replace() Method for Replacing Single Character
-
It replaces all the occurrences of the given character (oldChar) with the new character (newChar) and returns the new String object.
-
If the given character (oldChar) does not occur in the original string/file then a reference to the string object is returned without any changes.
* oldChar the old character. * newChar the new character. * return - A string derived from this string by replacing every public String replace(char oldChar, char newChar) { //Method declaration if (oldChar != newChar) { String ret = isLatin1() ? StringLatin1.replace(value, oldChar, newChar) : StringUTF16.replace(value, oldChar, newChar); //Checking the encoding of the Passed String if (ret != null) { return ret; //Returning replaced string if it is not null } } return this;//Returning original string if oldChar and newChar are same }
Above method takes a String object, oldChar, and newChar from the user as method Parameters. It checks for the encoding of the string (Latin or UTF) and according to that it replaces each occurrence of the character (oldChar) with the desired character (newChar).
2. replace() Method for Replacing Single Substring
-
It replaces all the occurrences of the given substring (target) with the new substring (replacement) and returns this new string.
-
If the given substring (target) does not occur in the original string/file then a reference to this string object is returned without any changes.
* target - The sequence of char values to be replaced * replacement - The replacement sequence of char values * return - The resulting string public String replace(CharSequence target, CharSequence replacement) { //Method declaration String trgtStr = target.toString(); //Converting 'target' CharSequence into the String String replStr = replacement.toString(); //Converting 'replacement' CharSequence into the String int thisLen = length(); //Calculating the length of the String object through which we have called replace() method int trgtLen = trgtStr.length(); //Calculating the length of 'target' string int replLen = replStr.length(); //Calculating the length of 'replacement' string if (trgtLen > 0) { if (trgtLen == 1 && replLen == 1) { return replace(trgtStr.charAt(0), replStr.charAt(0)); //calling replace() method for the characters if the length, target and replacement, both is 1 } boolean thisIsLatin1 = this.isLatin1(); //Checking any of the 3 parameters, which users have passed, are Latin or not boolean trgtIsLatin1 = trgtStr.isLatin1(); //Checking any of the 3 parameters, which users have passed, are Latin or not boolean replIsLatin1 = replStr.isLatin1(); //Checking any of the 3 parameters, which users have passed, are Latin or not String ret = (thisIsLatin1 && trgtIsLatin1 && replIsLatin1) //Calling appropriate implementation of replace() method based on the encoding (Latin or UTF) ? StringLatin1.replace(value, thisLen, trgtStr.value, trgtLen, replStr.value, replLen) : StringUTF16.replace(value, thisLen, thisIsLatin1, trgtStr.value, trgtLen, trgtIsLatin1, replStr.value, replLen, replIsLatin1); if (ret != null) { return ret; //Returning the new string object if it is not null } return this; //Returning original string object if it is null } else { // trgtLen == 0 int resultLen; try { resultLen = Math.addExact(thisLen, Math.multiplyExact( Math.addExact(thisLen, 1), replLen)); //Adding 1 in 'resultLen' and then multiplying it with 'replLen' and then adding whole result in the 'resultLen' and storing it into the 'resultLen' } catch (ArithmeticException ignored) { throw new OutOfMemoryError(); //Throwing OutOfMemoryError() if value of 'resultLen' exceeds 'int' range } StringBuilder sb = new StringBuilder(resultLen); //Creating object of the Class StringBuilder with length equal to 'resultLen' sb.append(replStr); //Appending 'replStr' into the StringBuilder object for (int i = 0; i < thisLen; ++i) { sb.append(charAt(i)).append(replStr); } return sb.toString(); //Converting StringBuilder object into the String object and returning it } }
Above method takes a String object, CharSequence target and replacement from the user as method Parameters. It checks for the encoding of the string (Latin or UTF) and according to that it replaces each occurrence of the substring (target) with the desired substring (replacement).
Above both implementations are given into the official code registry of JDK 14.0.2
Anyone, who has installed JDK(any version) on their machine can access these built-in codebase classes.
Conclusion
- replace() is the built-in method of the Java String class.
- It is useful when we want to make changes in our wrong string/file.
- It is a case-sensitive method.
- It looks for the exact match of character/substring in the string/file provided by the user and replaces it with a new character/substring.
- If the replace() method does not find the exact match of character/substring, it simply returns the original string.
Frequently Asked Questions (FAQs)
1. What are the different implementations available for the replace() method in Java String class?
There are various other built-in method implementations such as,
- replaceFirst()
- replaceAll()
2. Is replaceAll() and replace() work the same?
replaceAll() is the advanced implementation of replace() where we can use regular expressions to replace all characters of a string.