1

How is the String passed to this method getting reversed? If you pass "ABCD" the string become "DCBA", but I was thinking reverse(str.substring(1)) will call it self until it return "D" which will be concatenated with str.substring(0,1) which is D and the string returned to be "DD".JAVA programming Language.

private static String reverse(String str) {
    if (str.length() <= 1) {
        return str;
    }
    return reverse(str.substring(1)) + str.substring(0, 1);
}
1
  • 3
    Hi, welcome to SO. Do you know how recursion works? reverse(str.substring(1)) will call it self until it return "D" which will be concatinated with str.substring(0,1) wich is D and the string returned to be "DD" - No. Did you try debugging? Commented Sep 11, 2018 at 6:57

2 Answers 2

7

Your best bet with things like this is to work it through on paper and/or step through it statement by statement in the debugger built into your IDE.

  • reverse("ABCD") returns reverse("BCD") + "A". This is recursion. The call hasn't returned yet, because it needs the result of reverse("BCD") before it can add "A" to it and return.
    • reverse("BCD") returns reverse("CD") + "B", which waits for reverse("CD") to return
      • reverse("CD") returns reverse("D") + "C", which waits for reverse("D") to return
        • reverse("D") returns "D"
      • The result of reverse("D") + "C" is "DC", so now reverse("CD") can return "DC"
    • The result of reverse("CD") + "B" is "DCB", so now reverse("BCD") can return "DCB"
  • The result of reverse("BCD") + "A" is "DCBA", so now reverse("ABCD") can return "DCBA"
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the Quick response.
0

You can also use the following procedure to solve your problem:

String reversed = new StringBuilder(str).reverse().toString();

Also, according to the requirements about thread safety you can use StringBuffer or StringBuilder

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.