0

I am writing a method that returns a String with the specified letter doubled but it only returns the original value of s. I am relatively new to java and think this is due to Strings being immutable in java but I am not sure how to work around it. Any help with this method would be appreciated.

public static String doubleSpecificLetter(String s, String letter){
        String s2 = s;
        for(int i = 0 ; i < s2.length() ; i++) {
            if(s.substring(i, i + 1) == letter) {
                s2 = String.join(letter, s2.substring(0, i + 1), s2.substring(i + 1));
            }
        }

        return s2;
    }
  • Nope, the problem here isn't with immutability. The problem is that == doesn't actually check if the strings have the same content. As the linked duplicate says, use `.equals`. – D M Nov 25 '17 at 19:58
  • Your main mistake is the `x == letter` comparison, that should be `x.equals(letter)` as explained in the linked question. But I'm not sure that, even after that change, your method will cover a case like "bacadae","a" correctly. – Ralf Kleberhoff Nov 25 '17 at 20:00

0 Answers0