What is the String.replace method in Java?

The String.replace method replaces all the characters or substrings with the replacement character or string, and returns the replaced string as a new string.

Syntax

stringObj.replace(char oldChar, char newChar)

stringObj.replace(CharSequence oldText, CharSequence newText)

where:

  • the first parameter is the character/s that you want to replace.
  • the second parameter is the character/s you are using to replace the first.

Return value

This returns a string with the old characters replaced.

Replace all the matched characters of a String with another character

class Main {
public static void main( String args[] ) {
String str = "hat";
String newStr = str.replace('h', 'c');
System.out.println(newStr);
}
}

In the code above, we have created a hat string and called the replace method on the hat string. We then call replace('h', 'c'); this will replace all the character h in the string with the character c. This returns the replaced cat string.

Replace all the matched substring of a string with another string

class Main {
public static void main( String args[] ) {
String str = "babby babby";
String newStr = str.replace("bb", "dd");
System.out.println(newStr);
}
}

In the code above, we have created an str string with the value babby babby. We then call the replace method as replace("bb", "dd"). This replaces all of the bb substring with dd string and returns a new baddy baddy string.

Free Resources