Java - String replace() Method



The Java String replace() method is used to replace a single character or, a substring with a given value, from a string object.

This method searches the current string for the given character (or, substing), replaces all the occurrences with the given values, and retrieves returns the resultant string. This replacement is performed from the start of the string until its end. To replace something means to offer a suitable alternative, an equivalent, or to restore it to its original state.

This method has two polymorphic variants. The syntaxes of both the variants are shown below. The character variant of this method replaces every instance of the old characters in the string with the new characters. Similarly the Character Sequence variant replaces the given subtring.

For instance, replacing "cc" with "b" in the string "ccc" will result in "bc" rather than "cb".

Syntax

Following is the syntax for Java String replace() method −

public String replace(CharSequence target, CharSequence replacement)
or,
public String replace(char oldChar, char newChar) 

Parameters

  • target − This is the sequence of char values to be replaced. // first syntax

  • replacement − This is the replacement sequence of char values. // first syntax

  • oldChar − This is the old character. // second syntax

  • newChar − This is the new character. // second syntax

Return Value

  • The public String replace(CharSequence target, CharSequence replacement) method returns the resulting string. // first syntax

  • The public String replace(char oldChar, char newChar) method returns a string derived from this string by replacing every occurrence of oldChar with newChar. // second syntax

Example

In the example given below, a String object “str” is initialized. Then, two charSequence are initialized where the first charSequence in the above created string is replaced with the second charSequence −

import java.lang.*; 
public class StringDemo {
   public static void main(String[] args) {
      String str = "Tutorialspoint";
      System.out.println("string = " + str); 
      CharSequence s1 = "rialspoint";
      CharSequence s2 = "rix";      
      
      // replace sequence s1 with s2
      String replaceStr = str.replace(s1, s2); 
      
      // prints the string after replacement
      System.out.println("new string = " + replaceStr);
   }
}

Output

If you compile and run the above program, it will produce the following result −

string = Tutorialspoint
new string = Tutorix

Example

The following example shows the usage of Java String replace() method with the help of which all the occurrences of the old character “a” is replaced with the new character “b” −

import java.lang.*; 
public class StringDemo {
   public static void main(String[] args) {
      String str = "Hello how are how you";
      System.out.println("string = " + str); 
      CharSequence s1 = "how";
      CharSequence s2 = "why";      
      
      // replace sequence s1 with s2
      String replaceStr = str.replace(s1, s2); 
      
      // prints the string after replacement
      System.out.println("new string = " + replaceStr);
   }
}

Output

If you compile and run the program above, the output will be displayed as follows −

string = Hello how are how you
new string = Hello why are why you

Example

In the code given below, all occurrences of an old character is replaced with the new character using replace() method −

public class StringDemo {
   public static void main(String[] args) {
      String str = new String("Welcome to tutorials point training");
      System.out.println("The given string is: " + str);
      String newString = new String();
      newString = str.replace('t', 'f');
      System.out.println("The new string now is: " + newString);
   }
}

Output

On executing the program above, the output is obtained as follows −

The given string is: Welcome to tutorials point training
The new string now is: Welcome fo fuforials poinf fraining

Example

Now, all the occurrences of “” is replaced with “” using the replace() method −

public class StringDemo {
   public static void main(String[] args) {
      String str = new String("Next time there won't be a next time.");
      System.out.println("The string is: " + str);
      
      // Replacing the old string with new string
      String newString = new String();
      newString = str.replace("time", "day");
      System.out.println("The replaced string is: " + newString);
   }
}

Output

The output of the above program is as follows −

The string is: Next time there won't be a next time.
The replaced string is: Next day there won't be a next day.

Example

When the replacement or target is null, the replace() method throws the NullPointerException. The example that follows supports this −

public class StringDemo {
   public static void main(String argvs[]) {
      String s = "Next time there won't be a next time.";
      int size = s.length();
      System.out.println("The string is: " + s);
      String newString = null;
      s = s.replace(newString, "time ");
      System.out.println("The replaced string is: " + s);
   }
}

NullPointerException

While executing the above code we get the following output

The string is: Next time there won't be a next time.
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.CharSequence.toString()" because "target" is null
      at java.base/java.lang.String.replace(String.java:2954)
      at StringDemo.main(StringDemo.java:7)
java_lang_string.htm
Advertisements