-1
```
    String res = "";
    Solution.reverse("hellowolrd", res);
    System.out.println(res);

    public static void reverse(String str, String result) {
            if(str.length()==0) return; 
            result += str.charAt(str.length()-1); 
            reverse(str.substring(0,str.length()-1),result); 
        }


Why the res variable is empty when I print it out after calling reverse()

  • 1
    method is not returning anything and parameters are pass-by-value (in short, changing `result` inside the method does not change the corresponding variable on the calling method; `String` is immutable, but you could use a `StringBuilder` instead - or just return the result of concatenation) – user16320675 Apr 14 '23 at 16:14
  • Strings are immutable. you need to write this as a function and return the string – OldProgrammer Apr 14 '23 at 16:14

1 Answers1

0

Because result is a copy of the res you are passing onto the reverse method. Your original res stays the same.

One thing you could do is to use a StringBuilder which will modify the underlying storage.

    public static void reverse(String str, StringBuilder result) {
        if(str.length()==0) return; 
        result.append( str.charAt(str.length()-1) );
        reverse(str.substring(0,str.length()-1),result); 
    }
SomeDude
  • 13,876
  • 5
  • 21
  • 44