Replace() in Java - How to replace a character in a string
replace() in Java
This method replaces a character (or substring) in a string.
Syntax:
1 |
public String replace(char oldChar, char newChar); |
or
1 |
public String replace(String s1, String s2); |
How to Call the Method:
1 |
String newString = oldString.replace(char oldChar, char newChar); |
or
1 |
String newString = oldString.replace(String sub1, String sub2); |
Example:
1 2 3 4 5 6 7 8 9 10 |
public class Test { public static void main(String[] args) { String oldString = "ABC"; String newString = oldString.replace('A', 'B'); System.out.println("Old string: " + oldString); System.out.println("New string: " + newString); } } |
If you run this code on your computer, you will see the following in the console:
Commentary:
Initially, there is a variable called oldString with the text "ABC". To replace 'A' with 'B', we used the replace() method.
- As the first parameter, we set what we would like to replace. In this case it is the character 'A'
- As the second parameter, we set what we would like to replace it with. In this case with the character 'B'
As a result, we've got a new string with the text "BBC".
Please note, that the first string (oldString) wasn't changed when we used the replace() method. That means that the replace() method returned a new string.
That's all. You can find more articles in our Java Tutorial for Beginners.