-2

I have this method that removes a specific letter from the string

public static String removeSpecificLetter(String s, String letter){
    s.replaceAll(letter, "");
    return s;
}

and when I try to print it using the code below it returns "aabbcc"

public static void main(String[] args) {
    String s1 = "aabbcc";
    System.out.println(removeSpecificLetter(s1, "a"));
}
Juan Carlos Mendoza
  • 5,736
  • 7
  • 25
  • 50

1 Answers1

3

Strings are immutable in java, which means that:

s.replaceAll(letter, "");

doesn't replace the original value of s, but returns a new string with the replaced values. Hence return s; will return the same original String. You can do this:

public static String removeSpecificLetter(String s, String letter){
    return s.replaceAll(letter, "");
}

This time we return directly the newer String version with the values already replaced.

Juan Carlos Mendoza
  • 5,736
  • 7
  • 25
  • 50