Java String Replace

Java String replace method replaces all occurrences of old char to new char or old CharSequence to new CharSequence and return new String. If there is nothing to replace in the String, it will return same String.

Let’s say you need to convert "Java2blog" to "JavaTwoblog", you can simply use below syntax.

Syntax

There are two overloaded version of String’s replace method.

Example

Let’s understand with the help of Simple example.

When you run above program, you will get below output:

HelloWorld converted to : HellnWnrld

Above program will call public String replace(char oldChar, char newChar) version of replace method.

When you run above program, you will get below output:

How HashSet works in java

Above program will call public String replace(char oldChar, char newChar) version of replace method.

Internal implementation

public String replace(char oldChar, char newChar)

As you can see, above method finds first occurence of oldChar and then remaining string and replaces it with newChar.

public String replace(CharSequence target, CharSequence replacement)

Above code used Pattern and matcher to replace String.
That’s all about Java String replace method.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *