Java String replace() Method Tutorial

In this section, we will learn what the String replace() method is and how to use it in Java.

What is Java String replace() Method?

The Java String `replace()` method is used to search a string value for a specific character and replace it with a new one.

Java replace() Method Syntax:

public String replace(char searchChar, char newChar)

replace() Method Parameters:

This method takes two arguments:

The first one is the character that we want to be searched for and the second argument is the character that we want to be used as the replaced character in the string.

replace() Method Return Value:

The return value of this method is of type String and is a copy of the original string where we’ve replaced a specific character with a new one.

Note: this method does not change the original string!

replace() Method Exceptions:

This method does not throw an exception.

Example: using String replace() method

public class Simple {

    public static void main(String[] args)  {
        String hi = "Hello";
        String res= hi.replace('l','');
        System.out.println(res);
    }
}

Output: Heppo

Java Remove Character from String

Using this method, we can also remove a character from the target string if we want!

To do this, we set the second argument of this method to an empty character.

Note: still the original string stays the same, but the new value (the return of this method) won’t have the specified character anymore!

Example: removing character from String

public class Simple {

    public static void main(String[] args)  {
        String hi = "Hello";
        String res= hi.replace('l','');
        System.out.println(res);
    }
}

Output: Heo

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies