This post will discuss how to replace all occurrences of a character in string with another character in Java.

1. Using String.replace() method

The standard solution to replace all occurrences of a character in the String with another is with the String.replace() method. Its usage is demonstrated below:

Download  Run Code

Output:

A,B,C,D,E

 
If you need to replace each occurrence of a substring in the string with another string, you can use the String.replaceAll() method:

Download  Run Code

Output:

A, B, C, D, E

2. Using StringUtils.replaceChars() method

If you use the Apache Commons Lang library in your project, consider using the StringUtils.replaceChars() method, which is a null-safe version of the String.replace() method.

Download Code

Output:

A,B,C,D,E

That’s all about replacing all occurrences of a character in string in Java.