2

This piece of code reverses string parameter passed to it. I know that string is immutable. I seem not to understand what is going on. Where does it store the reversed string that it returns.

public static String reverseRecursively(String str) {

    //base case to handle one char string and empty string
    if (str.length() < 2) {
        return str;
    }

    return reverseRecursively(str.substring(1)) + str.charAt(0);

}
  • 9
    Have you tried writing out the results on paper, or working through it with a debugger? You may find it easier if you assign the final expression to a local variable before returning it. – Jon Skeet Oct 20 '13 at 06:41
  • @JonSkeet Yes, I have done that. It removes the first character of the string on every pass and finally returns the reversed string –  Oct 20 '13 at 06:43
  • @erictesting - There is the part ` + str.charAt(0)`... Try to step through code on paper as Jon suggested for string of 3 character... – Alexei Levenkov Oct 20 '13 at 06:45
  • @JonSkeet I think he's wondering where the values of each intermediate recursive call are stored. It's a good question actually which is why I erased his downvote. I did my best to answer but I'm sure you or someone else can answer in greater detail. – KyleM Oct 20 '13 at 06:49
  • @KyleM Thanks, at least someone understand my concern –  Oct 20 '13 at 06:51
  • @erictesting: You need to understand that it's not returning *once* - it's returning *lots* of times. That's why I've suggested using a local variable to see what's happened at each stage. – Jon Skeet Oct 20 '13 at 07:11

3 Answers3

1

Your reverseRecursively(str.substring(1)) + str.charAt(0) creates a new String object every time it is called.

mazaneicha
  • 8,794
  • 4
  • 33
  • 52
1

Where does it store the reversed string that it returns.

As the method shows, it calls itself recursively. Each time it is called it would add entries to the call stack. So, read about how the call stack works if you are concerned with the magic about where these "intermediate" results are stored.

KyleM
  • 4,445
  • 9
  • 46
  • 78
1

Here is a call diagram that illustrates data flow:

Reverse with a tail call dataflow

Vector source of the image

Each call returns a copy of string with first character placed last and rest being processed by further calls. References to these strings are stored on stack which grows with each call (more stack space is required to handle longer strings).

Basilevs
  • 22,440
  • 15
  • 57
  • 102
  • 2
    This diagram, and the OP's code, are exactly what a tail call is not. His recursive call is not in tail position, because before returning its result he adds `str.charAt(0)` to it. As for the diagram, if this were a tail call, the "returned value" would be exactly the same for each recursive invocation. There's nothing *wrong* with non-tail calls, but the wikipedia article on tail calls is totally irrelevant to this question. – amalloy Oct 20 '13 at 07:49