-3
public class recursiveReverse {

  public static String reverse(String str){ 
    if (str == null) {
      return null; 
    } 
    if (str.length() <= 1) {
      return str;
    } 
    return reverse(str.substring(1)) + str.charAt(0); 
  }

  public static void main(String[] args) {
    reverse("car");
  }
}

I get to the first time the if (str.length() <= 1) returns true, then I get lost.

  • 4
    Have you tried stepping through it in a debugger? – resueman Dec 04 '15 at 20:28
  • yeah, it just got to the recursive call and stayed there. Wasn't much help, but there's a high chance there's some better way to step through it that I'm unaware of. – Emilia Clarke Dec 04 '15 at 20:30
  • 1
    The only way to understand recursion is to go through it iteration by iteration either with paper and pencil or in debugger. – PM 77-1 Dec 04 '15 at 20:32
  • 1
    Definitely have a read through the question @dnault linked to - that should help – mikej Dec 04 '15 at 20:38

3 Answers3

1

Like others have pointed out, you would be well served by stepping through the code under the debugger.

Here's the code with "printf's":

Test.java =>

public class Test {

  public static String reverse(String str){ 
    System.out.println("-->str=" + str);
    if (str == null) {
      System.out.println("<--str=null");
      return null; 
    } 
    if (str.length() <= 1) {
      System.out.println("<--str=str");
      return str;
    } 
    String result = reverse(str.substring(1)) + str.charAt(0); 
    System.out.println("<--result=" + result);
    return result;
  }

  public static void main(String[] args) {
    reverse("car");
  }
}

Output, java Test =>

-->str=car
-->str=ar
-->str=r
<--str=str;
<--result=ra
<--result=rac
paulsm4
  • 114,292
  • 17
  • 138
  • 190
  • this is manipulated output :p .. System.out.println("<--str=str"); should be System.out.println("<--str="+str); – StackFlowed Dec 04 '15 at 20:40
0

Let's take it one line at a time.

If the string to reverse is null, the method returns null.

If the string to reverse as a length <= 1, it is returned as is.

If the string is longer, the it will return the reversed sub string starting at position 1, concatenated with the first character of the string.

So: reverse("a") --> a

reverse ("ab") -> reverse("b") + "a" -> "ba"

reverse ("abc") -> reverse("bc") + a -> reverse("c") + "b" + "a"

etc.

Richard St-Cyr
  • 970
  • 1
  • 8
  • 14
0

It is recursive call to reverse function till the length of string reaches one character.

In above case the string to reverse is CAR. In first pass it will become { reverse (AR) + C} In second pass it will Become { reverse(R) +A } In third pass it get value of reverse(R) as R

Which will become R +A +C =RAC as final answer.