The Java replace method of String

The String replace method of Java is used to replace the existing character(s) in the given string to the new given character(s).

A few important points to be noted:

  • Since Java string is immutable, once created, it cannot be changed. The replace method returns a new string which is the replaced string.
  • This method replaces all occurrences of the matched character in the string.
  • You may get the new string in another String variable to keep it.
  • The source string remains the same after using the replace method.
  • There are two implementations of Java replace method as shown in the syntax below.

Syntax of using replace string method

Following are the ways of using the replace() Java method:

First way:

str.replace(oldChar, newChar)

  • Where oldChar is the existing character in the string
  • newChar is the character to be replaced with the existing character.
  • If oldChar does not exist in the str, the replace method reruns the reference to this string object.

Second way:

replace(CharSequence target, CharSequence replacement)

CharSequence target is the sequence of existing char sequence.

In that case, the replace method begins replacement from the beginning of the string. For example, if you specify the “yy” to be replaced with “za” in the given string containing “yyy” then the resultant string will be “zay”.

A NullPointerException exception is raised if target or replacement is null.

See the following section for the examples with code.

An example of using Java string replace method (char)

For this example, a string is created and in the string character ‘R’ is replaced by ‘r’ i.e. capital R is replaced by small ‘r’ character.

The Output:

Original String: Replace method to change chaRacteRs

After replace: replace method to change characters

An example of replace method with CharSequence

In the following example, the word “password” is replaced in the string to the asterisk (*) characters. You may notice, double quotes are used for the charSequence parameters for both existing and to be replaced with characters.

The output of the code is:

Enabling to use the charSequence means you may specify CharBuffer, Segment, String, StringBuffer there, as these are subclasses of charSequence.