Skip to content

Java String replace Example

Java String replace Example shows how to replace string with other string in Java. The example also shows how to replace a character, first occurrence or all occurrences of the string in Java.

How to replace a character in String in Java?

To replace a character in the string, you can use the replace method of Java String class.

This method replaces all the occurrences of the specified character with a new character and returns the result in a new String.

Example

Output

Note: If the specified character does not exist in the String, then the reference to the original string is returned. Otherwise, a new String object is created as a result of replacement and returned.

Please also note that, since the string is immutable (cannot be changed once created), the replace method does not change the original String but returns a new String as given below.

Output

Make sure to assign the result of the replace method back to the original String if you want the result in the original string.

How to replace string with another string?

To replace string with another string, you can use the replace method of String class.

This method replaces all the occurrences of a specified string with the replacement string and returns result in a new String.

Example

Output

If the string does not contain the specified string, the reference of the original string is returned. Otherwise, a new string is created as a result of replacement and returned.

Important note: Even though the name of the method is “replace”, it replaces ALL the occurrences of the specified string in a given string, not just one as given below.

Output

How to replace the first occurrence of a string with other string in Java?

To replace only the first occurrence of a string within the string, use the replaceFirst method.

This method replaces the first substring that matches the regular expression with the replacement. It returns the result in a new string object.

Output

Important Note: The replaceFirst method accepts regular expression while the replace method does not. For example, below given code replaces the first digit of the string with the empty string using a regular expression.

Output

If you want to specify a regular expression, you should use the replaceAll method instead.

How to replace a string with Apache Commons library?

If you are using the Apache Commons library, you can use the replace method of the StringUtils class as given below.

Output

This example is a part of the String in Java tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.