Java String Replace Character

Java String replace character example shows how to replace a character in the string using the replace and replaceFirst methods of the String class.

How to replace a character in a string?

The Java String class provides the replace method that takes two char arguments that can be used to replace a character in a string.

This method replaces all occurrences of the old character with the new one in the string.

Output

As you can see from the output, the character ‘c’ is replaced with the character ‘b’ in the string. Instead of the character version of the replace method, you can also use the overloaded replace method that accepts two string arguments instead of the character arguments like given in the below code example.

Output

The replace method replaces all the old characters in the string with the new one. See below given example.

Output

If you want to replace only the first instance of the character with the new one, you can use the replaceFirst method instead of the replace method.

Here is the same example with the replaceFirst method instead of the replace method.

Output

As you can see from the output, only the first instance of the character ‘c’ was replaced in the string.

Additionally, the replace method is case-sensitive. It means that the case of the character to replace must be the same, otherwise, the replacement will not happen.

Output

As you can see from the output since the case of the character we want to replace does not match with the case of the character in the string, no replacement was done. If you want to do the replacement regardless of the case, you can either convert the string to uppercase or to lowercase and then do the replacement as given below.

Output

Lastly, both the replace and replaceFirst methods return a new string having replaced content. The original string object remains as-is.

Output

If you want the replacement results back in the original string object, you need to assign the return value of these methods to the original string reference as given below.

Output

If you want to learn more about the string in Java, please visit the Java String tutorial.

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

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

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