W3docs

How do I replace a character in a string in Java?

To replace a character in a string in Java, you can use the String.replace(char oldChar, char newChar) method.

To replace a character in a string in Java, you can use the String.replace(char oldChar, char newChar) method. This method returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.

Note that Java strings are immutable, so you must reassign the result to a variable to keep the changes.

Here is an example of how you can use this method:


String str = "Hello World!";
str = str.replace('o', 'a');
System.out.println(str); // prints "Hella Warld!"

Alternatively, you can use the String.replace(CharSequence target, CharSequence replacement) method, which replaces all occurrences of the specified character sequence with the specified replacement string.

Here is an example of how you can use this method:


String str = "Hello World!";
str = str.replace("o", "a");
System.out.println(str); // prints "Hella Warld!"