Java String replace()

The String.replace() API searches for a literal substring and replaces each occurrence with the replacement string. The search for substring starts from the beginning of the string i.e. index 0.

Note that a similar method String.replaceAll() searches and replaces all substrings using regular expressions.

1. String.replace() Method

The replace() method is an overloaded method and comes in two versions:

public String replace(char oldChar, char newChar);

public String replace(CharSequence target, CharSequence replacement);
  • The first method accepts the char types. It searches the string for specified oldChar and replaces each occurrence of oldChar with the newChar.
  • The second method accepts the String types. It searches the string for the specified target substring and replaces each occurrence with the replacement.

2. Replace All Occurrences of a Character

The following Java program replaces all occurrences of the letter ‘o’ (lower case) with the letter ‘O’ (upper case).

String message = "Hello world !!";

Assertions.assertEquals("HellO wOrld !!", message.replace('o', 'O'));

3. Replace All Occurrences of a Substring

The following Java program replaces all occurrences of the substring “Hello” with the new String “Hi”.

String message = "Hello world !!";

Assertions.assertEquals("Hi world !!", message.replace("Hello", "Hi"));

4. Regex is Not Supported

Regular expressions are not allowed as method arguments. If we use a regex pattern, it will be treated as a literal string.

In the following program, the regex [H] pattern will match character H is regex is supported. But replace() does not support regex so there are no matches found.

String message = "Hello world !!";

Assertions.assertEquals("Hello world !!", message.replace("[H]", "h"));

5. Null is Not Allowed

The 'null' is not allowed as both method arguments. It will throw NullPointerException.

Assertions.assertThrows(NullPointerException.class, () -> {
  message.replace(null, "O");

Assertions.assertThrows(NullPointerException.class, () -> {
  message.replace("o", null);

Happy Learning !!

Java String Doc


Notify of
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.