Java Data Type How to - Replace letters in a String








Question

We would like to know how to replace letters in a String.

Answer

The replace() method takes an old character and a new character as arguments.

It returns a new String object by replacing all occurrences of the old character by the new character. For example,

public class Main {
  public static void main(String[] args) {
    String oldStr = new String("tooth");
    String newStr  = oldStr.replace('o', 'e');
    System.out.println(newStr);
  }
}

The code above generates the following result.