Understanding the Java String Replace Method

shutterstock_125786036A String, a sequence of characters, is one of the most frequently used data types in almost every programming language. Every program from basic “Hello world” to enterprise-level applications involves a manipulation of strings, and understanding the use of string manipulation methods is integral in a programming language. In Java, a String is a special class and an object of this class is immutable, which means content of a string cannot be modified once it is created. Manipulation of a string returns a newly created String object when its content is modified. Some of the important manipulation methods of String are ‘split’, ‘trim’, ‘toLowerCase’, ‘toUpperCase’ and ‘replace’.

For more Java tutorials, take a course at Udemy.com.

What is Java String Replace?

In Java, String ‘replace’ and its variants are used to replace a character, string or a regular expression from a String object with a character or string replacement. When there is a change in the String object while performing ‘replace’, a new String is returned whereas in a case of no change, the same object is returned.

Java String Replace Method Syntax

String replace (char charToReplace, char replacementChar)

In the above “replace” method format, each occurrence of a character ‘charToReplace’ in a string is replaced with the character ‘replacementChar’ and a new String object containing this character sequence is returned.

How Java String replace Method Works?

The following code snippet demonstrates how a character is replaced from one string to another character.

String sampleString = new String ("Understanding Java String Replace.");

String resultantString = sampleString.replace ('J', 'C');

System.out.println ("Output:");

System.out.print ("After a replace method call: ");

System.out.println (resultantString);

In the above code snippet, the ‘replace’ method finds and replaces all the occurrences of the‘J’ character in ‘sampleString’ with a ‘C’ character and saves a result in a new String object named ‘resultantString’ with following output on console:

Output:

After a replace method call: Understanding Cava String Replace.

Replacing a String object using ‘replace’ is case sensitive, therefore, replacing the ‘J’ only replaces a capital case ‘J’ rather than a lower case ‘j’.

To further explore Java Strings, take a course at Udemy.com.

Java String Replace method to replace character sequence in string

The ‘replace’ method also exists in a Java String class with a different parameter signature (method overloading). This method replaces all the occurrences of string literal matches in String object with the replacement string literal. Following is the format of this method.

String replace (CharSequence targetToMatch, CharSequence replacement)

When either a ‘targetToMatch’ or ‘replacement’ character sequence is null, this String ‘replace’ method throws a NullPointerException exception.  The following example demonstrates the String ‘replace’ method with the above format.

String sampleString = new String ("Best programming environment is Windows OS.");
String resultantString = sampleString.replace ("Windows OS", "Mac OS");
System.out.println ("Output:");
System.out.print ("After a replace method call: ");
System.out.println (resultantString);

In the above code snippet, the ‘replace’ method finds and replaces all the occurrences of “Windows OS” character sequence in ‘sampleString’ with a “Mac OS” literal and saves a result in a new String object named ‘resultantString’ with following output on console:

Output:

After a replace method call: Best programming environment is Mac OS.

Java String Replace Variant ‘replaceAll’

Unlike the ‘replace’ method, ‘replaceAll’ supports regular expressions. The capability of ‘replaceAll’ makes the complex search of substrings possible within a string object. After a search, each matched substring is replaced with the given replacement.  The following is a format of ‘replaceAll’ method:

String replaceAll (String regEx, String replacement)

In the above format, the “regEx” string object is a regular expression that is used to search the string and replaces all matched substrings with the ‘replacement’. This Java String ‘replace’ method in addition to a NullPointerException exception throws a PatternSyntaxException exception when a provided regular expression format is not valid. The following examples show a basic use of regular expression:

Code snippet 1:

String sampleString = new String ("Remove All Spaces");
String resultantString = sampleString.replaceAll ("\\s+","");
System.out.println ("Output:");
System.out.print ("After a replaceAll method call: ");
System.out.println (resultantString);

Output:

After a replaceAll method call: RemoveAllSpaces 

Code snippet 2:

String sampleString = new String ("Remove first word");
String resultantString = sampleString.replaceAll ("^\\w+\\s","");
System.out.println ("Output:");
System.out.print ("After a replaceAll method call: ");
System.out.println (resultantString);

Output:

After a replaceAll method call: first word

Code snippet 3:

String sampleString = new String ("Remove all text before Java is best");
String resultantString = sampleString.replaceAll (".*before", "Only");
System.out.println ("Output:");
System.out.print ("After a replaceAll method call: ");
System.out.println (resultantString);

Output:

After a replaceAll method call: Only Java is best

Due to the advanced search option in ‘replaceAll’, it is the most frequently used variant of the String ‘replace’ method compare to other methods. In the aforementioned examples, the following basic matching symbols and meta-characters of the regular expression are used:

  • The meta-character ‘\s’ is a single whitespace while ‘\s+’ denotes all of the whitespaces in string (refer to code snippet 1).
  • The meta-character ‘\w’ is a single word character while ‘\w+’ denotes a word in string (refer to code snippet 2).
  • Symbol ‘.’ represents any character in a string.
  • Symbol ‘.*’ represents any number of characters in a string starting from the position of ‘.’ and ends at the last character of string (‘*’ represent all content starts from ‘.’) or at a character sequence after ‘*’ symbol (in case of code snippet 2).

Java String Replace Variant ‘replaceFirst’

This variant of string ‘replace’ method is the same as the ‘replaceAll’ variant except that it only replaces the first occurrence of matched string pattern based on the regular expression. The following is a format of ‘replaceFirst’ method.

String replaceFirst (String regEx, String replacement)

The ‘replaceFirst’ method throws the same exceptions as string ‘replace’ and its other variant. The following example demonstrates the replacement of only the first occurrence of matched pattern using ‘replaceFirst’.

String sampleString = new String ("String replacement using replaceFirst method.");
String resultantString = sampleString.replaceFirst ("rep", "Rep");
System.out.println ("Output:");
System.out.print ("After a replaceFirst method call: ");
System.out.println (resultantString);

Output:

After a replaceFirst method call: String Replacement using replaceFirst method.

In the above code snippet, unlike the ‘replace’ string method, only first occurrence of a ‘rep’ character sequence is replace while the other occurrence is still the same as before.

To learn more Java essentials, check out this tutorial