There are two variants of replace() method of String. They are as follows:

(1.) String replace(char oldChar, char newChar)
(2.)String replace(CharSequence target, CharSequence replacement)

(1.) String replace(char oldChar, char newChar)

This method returns a string resulting from replacing all occurrences of oldChar in this string with newChar. If there is no match for oldChar then a reference to original String is returned.

Lets take an example to understand this.

package com.masterjavatutorial;
public class Main {
     public static void main(String[] args) {
	 String str = "This is String demo program demo";
	 String charReplaceStr = str.replace('m','7');
	 System.out.println("String after Character Replacement = "+charReplaceStr); 
     }
}

This program would replace character ‘m’ with character ‘7’.

Output of the above program is as below:

String after Character Replacement = This is String de7o progra7 de7o

(2.)String replace(CharSequence target, CharSequence replacement)

This method returns a string resulting from replacing all occurrences of substring in this string with new substring. If there is no match for substring then a reference to original String is returned.

package com.masterjavatutorial;
public class Main {
   public static void main(String[] args) {
     String str = "This is String demo program demo";
     String replace = str.replace("demo","test"); 
     System.out.println("New String after replace = "+replace); 
  }
}

This program would replace substring “demo” with substring “test”.

Output of the above program is as below:

New String after replace = This is String test program test

Leave a Reply