What are the common replace() methods of String class in Java?

The String class provides four different kinds of replace() methods in Java. Each of the methods addresses a specific use case. Their names are listed below:
  1. replace(char, char)
  2. replace(String, String)
  3. replaceAll(String, String)
  4. replaceFirst(String, String)
Moving forward with the post, we will see how each method works. We’ll also look into the need of using the above in different use cases.

Java String replace() method

The Java String replace() method is used to replace a specified character with the given character both passed as parameters. This method is suitable for replacing any character in a String with some other character of your choice.

Method Header


String replace(char oldChar, char newChar)

String replace(CharSequence target, CharSequence replacement)

Method Parameters

The method takes two ‘char’ type parameters or arguments.
  • char oldCharacter holds the character to be replaced.

  • char newCharacter holds the character that will be used in place of the oldCharacter.

  • target: The sequence of characters to be replaced. This is a CharSequence, such as a String.
  • replacement: The sequence of characters that replaces target. This is a CharSequence, such as a String.

Return Type

The method String replace returns the updated string after replacing the desired character.

Example

Let’s have a look at different simple examples to understand how this method works.

public class Driver {

	public static void main(String[] args) {

	      String myString = "An apple a day, keeps the doctor away!";
		System.out.println("Original Sentence: \t\t\t" + myString);

		// Example 1 using String replace(char, char)
		char oldCharacter = 'a'; // replacing character
		char newCharacter = 'A'; // character to be replaced
            String updatedString = myString.replace(oldCharacter, newCharacter);    
		System.out.println("After replacing '" + oldCharacter + "' with '" + 
		// 'a' is replaced and not with 'A' as the method is case sensitive
		newCharacter + "': \t\t" + updatedString);
		
		// Example 2 using String replace(String, String)
		String oldString = "apple";
		String newString = "orange";
		// using the method String replace		
            String updatedString1 = myString.replace(oldString, newString); 
            System.out.println("Replacing '" + oldString + "' with '" + 
        		newString + "': \t" + updatedString1 + "\n");
	}
}

Output

Original Sentence: An apple a day, keeps the doctor away! After replacing 'a' with 'A': An Apple A dAy, keeps the doctor AwAy! Replacing 'apple' with 'orange': An orange a day, keeps the doctor away!
Note: You’re advised to get acquainted with regular expressions aka regex before moving forward.

Exceptions Related to replace() Parameters

The replace() method does not throw runtime exceptions for invalid parameters. However, null values for target or replacement can lead to NullPointerException if not handled properly.

Example:

String input = null;
try {
    String result = input.replace("a", "b");
    System.out.println(result);
} catch (NullPointerException e) {
    System.out.println("Null input encountered: " + e.getMessage());
}

Output:

 Null input encountered: Cannot invoke "String.replace(Object, Object)" because "input" is null

To avoid this, always check for null values before invoking replace():

if (input != null) {
    String result = input.replace("a", "b");
}

Behavior with Different Data Types and Parameter Variations

The replace() method provides flexibility in handling both characters and sequences. However, it is important to understand how the method behaves with different input combinations:

  • Case Sensitivity: The replace() method is case-sensitive, so "a" and "A" are treated as distinct characters or sequences.
  • Non-Matching Parameters: If oldChar or target does not exist in the string, the original string is returned unchanged.
  • Empty String: Replacing with an empty string effectively removes the specified characters or sequences.

Examples:

// Case sensitivity
String caseTest = "hello".replace("H", "h");
System.out.println(caseTest); // Output: hello (unchanged)

// Non-matching parameters
String noMatch = "hello".replace("z", "y");
System.out.println(noMatch); // Output: hello (unchanged)

// Empty string replacement
String emptyReplace = "banana".replace("a", "");
System.out.println(emptyReplace); // Output: bnn

Java String replaceAll() method

The Java String replaceAll() method replaces EVERY single occurrence of a regular expression passed as a parameter with the desired String. This means, that every copy of regex is updated by the replacement string.

Method Header


public String replaceAll(String regularExpression, String replacementStr)

Method Parameters

This method takes two ‘String’ type arguments.
  • String regularExpression holds the regex (pattern) to be replaced.

  • String replacementStr is the String that will be used in place of the regex.

Return Type

The method returns a new string after replacing all occurrences of the regex.

Example

This method is commonly used to update huge data records. For a deeper understanding, let’s look at different examples of the replaceAll() method.

public class Driver1 {

	public static void main(String[] args) {

		String myString = "Mastering a programming language begins with great logic building!";
		System.out.println("Original Sentence: \t\t\t" + myString);

		String regex = "[\sa]"; // This regex is used to remove all spaces and a(s) in the string
		String replacementStr = "";
		// using the method String replaceAll(); to remove ALL spaces
		System.out.println("After replacing \"" + regex + "\" with \"" + replacementStr + "\": \t"
				+ myString.replaceAll(regex, replacementStr) + "\n");
	}
}

Output

Original Sentence: Mastering a programming language begins with great logic building! After replacing "[ a]" with "": Msteringprogrmminglngugebeginswithgretlogicbuilding!

Java String replaceFirst() method

The Java String replaceFirst() method replaces the ONLY FIRST occurrence of the regex passed to this method.

Method Header


public String replaceFirst(String regularExpression, String replacementStr)

Method Parameters

This method takes two ‘String’ type arguments.
  • String regularExpression holds the regex (pattern) to be replaced.

  • String replacementStr is the String that will be used in place of the regex.

Return Type

The method returns a new string after replacing only the FIRST occurrence of the regex.

Example

This method can be used when you want to update just the first record found of your matching argument. Let’s explore how it works in the example below.

public class Driver2 {
	
	public static void main(String[] args) {

		String myString = "Good Morning. You wonders of Nature. Today is a great day to be happy.";
		System.out.println("Original Sentence: \t\t" + myString);

		String regex = "\\."; // regex to update period / full stop
		String replacementStr = "!";
		// using the method String replaceFirst();
		// to remove first period(.) with exclamation(!) mark
		System.out.println("After replacing '" + regex + "' with '" + replacementStr + "': \t"
				+ myString.replaceFirst(regex, replacementStr));
	}
}

Output

Original Sentence: Good Morning. You wonders of Nature. Today is a great day to be happy. After replacing '\.' with '!': Good Morning! You wonders of Nature. Today is a great day to be happy.

Handling Special Characters in Regular Expressions

When using replaceAll(), the first parameter is treated as a regular expression (regex). Certain characters have special meanings in regex, such as:

  • .: Matches any character.
  • *: Matches zero or more occurrences of the preceding element.
  • +: Matches one or more occurrences of the preceding element.
  • []: Defines a character set.
  • \: The escape character for special characters.

To treat these characters as literals, you need to escape them by prefixing them with a double backslash \\.

Example:

public class SpecialCharactersExample {
    public static void main(String[] args) {
        String input = "Price: $100 (discounted)";

        // Replace parentheses with brackets
        String result = input.replaceAll("\\(|\\)", "[");

        System.out.println("Original: " + input);
        System.out.println("Modified: " + result);
    }
}

Output:

 Original: Price: $100 (discounted)
 Modified: Price: $100 [discounted]

Examples Demonstrating Escaping Special Characters

Escaping special characters is essential when you want the regex engine to treat them as literal characters:

Example 1: Replacing Dots

public class EscapeDotExample {
    public static void main(String[] args) {
        String input = "www.example.com";

        // Replace dots with underscores
        String result = input.replaceAll("\\.", "_");

        System.out.println("Original: " + input);
        System.out.println("Modified: " + result);
    }
}

Output:

 Original: www.example.com
 Modified: www_example_com

Example 2: Replacing Curly Braces

public class EscapeBracesExample {
    public static void main(String[] args) {
        String input = "{name: John, age: 30}";

        // Replace curly braces with parentheses
        String result = input.replaceAll("\\{|\\}", "(");

        System.out.println("Original: " + input);
        System.out.println("Modified: " + result);
    }
}

Output:

 Original: {name: John, age: 30}
 Modified: (name: John, age: 30)

Locale Sensitivity in Replace Methods

The behavior of replace methods can be influenced by the system's locale settings. Locale sensitivity affects certain characters, especially in non-English locales where characters might have multiple representations or cases. For example:

  • In the Turkish locale, the uppercase of i is İ (dotless I).
  • In the German locale, ß (sharp S) may convert to SS.

Implications:

Locale differences can lead to unexpected results when performing case-insensitive replacements or handling characters with locale-specific representations.

Example:

import java.util.Locale;

public class LocaleSensitivityExample {
    public static void main(String[] args) {
        String input = "istanbul";

        // Change default locale to Turkish
        Locale.setDefault(new Locale("tr"));

        // Replace 'i' with 'I'
        String result = input.replace("i", "I");

        System.out.println("Original: " + input);
        System.out.println("Modified: " + result);
    }
}

Output:

 Original: istanbul
 Modified: Istanbul

To avoid locale-related issues, explicitly set the locale or use methods that account for locale differences, such as Locale.ROOT.

Conclusion

So those were some basics of using the replace() methods in Java. As always, we highly recommend learning by practice. Until next time, keep learning and keep growing!