Java String.replace() method explanation with example

Java String.replace() method explanation with example:

Java String class comes with an inbuilt method to replace any specific character or string with a different character or string. This is a built-in method. Since String is immutable in Java, it creates a new string and returns that string.

In this post, we will learn how to use the replace() method with its definition and example.

Definition of String.replace():

The replace() method can be used to replace all occurrences of a character in a string or we can use it to replace all substrings.

For character arguments, It is defined as like below:

public String replace(char oldCh, char newCh)

Here,

  • oldCh is the old character and newCh is the new character. It replaces all occurrences of the old character in the string with the new character.
  • It creates a new string by replacing all old characters with the new character and returns it.
  • If the old character is not found, it returns the same reference of the caller string i.e. it doesn’t create another string object.

Similarly, it is defined as like below for character sequences:

public String replace(CharSequence str, CharSequence newStr)
  • It works similar to the above one. It finds the substrings str in the caller string and replaces it with newStr for each occurrences. The replacement process starts from the beginning of the string to the end.
  • It creates a new string and returns that string.
  • If any of the parameter is null, it throws NullPointerException.

Example of String.replace:

Let’s learn how String.replace works with different examples.

public class Main {

    public static void main(String[] args) {
        String str = "hello world";

        String s = str.replace('o', 'x');

        System.out.println(s);
        System.out.println(str == s);
    }
}

Here, we are using replace to replace all occurrences of ‘o’ with ‘x’. The returned value is stored in the variable s. The last line is checking if str and s are pointing to the same reference or not.

It will print:

hello world
false

As you can see here, it prints false because str and s are both pointing to different references.

Now, let’s try to replace a character which is not there in the string:

public class Main {

    public static void main(String[] args) {
        String str = "hello world";

        String s = str.replace('z', 'x');

        System.out.println(s);
        System.out.println(str == s);
    }
}

Since ‘z’ is not in str, the replace method will return the same string instance.

hello world
true

It prints true because both str and s are pointing to the same instance.

String.replace() with strings:

Let’s try String.replace() with strings to replace substrings.

public class Main {

    public static void main(String[] args) {
        String str = "hello world hello world hello world";

        String s = str.replace("world", "universe");

        System.out.println(s);
    }
}

It will replace all occurrences of “world” with “universe”. It will print:

hello universe hello universe hello universe

Replacement starts from left:

The replacement starts from left. For example:

public class Main {

    public static void main(String[] args) {
        String str = "aaaaaa";

        String s = str.replace("aaa", "b");

        System.out.println(s);
    }
}

It will print bb, because it replaces the first three ‘a’ with b and the last three ‘a’ with b.

Let me change it to aaaaa:

public class Main {

    public static void main(String[] args) {
        String str = "aaaaa";

        String s = str.replace("aaa", "b");

        System.out.println(s);
    }
}

The replacement starts from left. So, it will replace the first 3 ‘a’ with ‘b’.

baa

Exception:

As explained above, it will throw NullPointerException if any of the parameter is null.

public class Main {

    public static void main(String[] args) {
        String str = "aaaaa";

        String s = str.replace("aaa", null);

        System.out.println(s);
    }
}

It will throw:

Exception in thread "main" java.lang.NullPointerException
	at java.base/java.lang.String.replace(String.java:2158)
	at com.company.Main.main(Main.java:8)

Java string replace NullPointerException

You might also like: