All Posts

Java replace() method

Java replace() method

The Java replace() method is used to replace occurrences of a specified character or substring within a string with a new character or substring.

It returns a new string replacing all the old char or CharSequence with new char or new CharSequence in the given original string. Since JDK 1.5, the replace() method allows you to replace a sequence of char values.

replace() method signatures

The replace() method is overloaded and has the following signatures:

replace(char oldChar, char newChar) : This method replaces all occurrences of the character oldChar with newChar.

replace(CharSequence target, CharSequence replacement) : This method replaces all occurrences of the sequence specified by target with the sequence specified by replacement.

Example

The following Java program helps you understand the use of the replace() method.

package com.testingdocs.stringmethods;

public class ExampleProgram {

	public static void main(String[] args) {
		String str = "www.TestingDocs.com";
        // replace() method demo
		System.out.println("Original string : " + str);
		System.out.println("Replaced string : " + 
str.replace("www.","https://"));
	}
}

Program Output

The program output is as below:

Original string : www.TestingDocs.com

Replaced string : https://TestingDocs.com

 

Java replace method

Java Tutorials

Java Tutorial on this website: