java.lang.String replace()

Description :

This java tutorial shows how to use the replace() method of java.lang.String class. This method returns a String datatype which which is a result in replacing oldChar with the newChar as declared on the method arguments. This is basically changing a character to a new character which results to a new String object.

Method Syntax :

public String replace(char oldChar,char newChar)

Parameter Input :

DataType Parameter Description
char oldChar the character we want to get replaced
char newChar the new character we want to appear on our String

Method Returns :

This method returns a String datatype which corresponds to a new String generated or derived in replacing the oldChar to newChar parameter.

Compatibility Version :

Since the beginning

Exception :


Discussion :

As we have already iterated many times on our previous articles, the original String object will not be changed once its already instantiated. Meaning to say, the new String generated during the replacement of characters would result to new String object. Thus, if we want to have access to the new String object we would need to reassign it to the old String object or we could create a new String object assignment.

For instance :

String str = "test";

You might be expecting that all ‘e’ on the str object will be replaced with character ‘t’. Do you think the code above will print “ttst”? You will be surprised that the output will be the original content of our string.

Then you might be wondering now, how to get the new String value. You can do this to print the new string object generated from replacing the oldChar to newChar.

str = str.replace('e','t');

Java Code Example :

This example source code demonstrates the use of replace() method of String class. Basically this source code just prints the resultant string after using the replace() method of String class. Always remember that the string would never change once it is instantiated thus the expression this.replace(oldChar,newChar) would not change the value of String. If we want the value out of the replace method, we should assign it to a new variable. We then print the full name using the classic System.out.println() method.


 * Java sample code to replace character

public class StringReplaceDemo {

    public static void main(String[] args) {
        String strValue = "Name|age|Country";
        // method chaining, multiple replacement
        strValue = strValue.replace("|", "/").replace('C', 'c');


Sample Output :

Running the replace() method example source code of java.lang.String class will give you the following output

String replace method example

String replace method example

 Suggested Reading List :