0
private static String stringReverseRecursive(String str)
   {
       // saves the last letter of the word in the variable c
    char c = str.charAt (str.length()-1); 
       // take the last letter saved in c and joins the sub string of everything without the first letter and runs it again.
       return c + stringReverseRecursive((str.substring(0,str.length()-1))); 

   }

When I try to call the function then the compiler gives me an error saying that it goes out of range. I think there is something wrong with the lat line and the char c line.

6
  • Hi, Recursive methods need a base case where if it's true the recursion ends... Otherwise it won't stop executing until an error such as the one you've described above happens or max stack depth is reached e.g. if (str.length() == 0) { return str; } If you're looking for more info on recursion, you can give this a read: tripwiretech.blogspot.co.nz/2014/09/… Commented Oct 25, 2017 at 1:49
  • What happens if you reverse the empty string? Because your recursive call will always reduce to a call with the empty string, and if you don't handle that special case, your method doesn't work at all. Commented Oct 25, 2017 at 1:49
  • @TripWire do you mean that I should put everything in the method in else Commented Oct 25, 2017 at 1:52
  • Are you trying to reverse a string, as the method name implies, or are you trying to find the last letter of a string? Commented Oct 25, 2017 at 1:59
  • 1
    "the compiler gives me an error" no, it doesn't. What you're seeing is a runtime error. Commented Oct 25, 2017 at 2:13

1 Answer 1

1
private static String stringReverseRecursive(String str)
{ 
    if (str.isEmpty()) {

        return str;
    }

   // saves the last letter of the word in the variable c
   char c = str.charAt (str.length()-1); 
   // take the last letter saved in c and joins the sub string of everything without the first letter and runs it again.
   return c + stringReverseRecursive((str.substring(0,str.length()-1))); 

}

You want to check if the length is 0, to cater for an empty string e.g. ""

The if statement allows your code to complete execution and can be referred to as the base case.

Sign up to request clarification or add additional context in comments.

2 Comments

I'd prefer String#isEmpty() to a length() == 0 test.
Thanks Elliott, that is better and I’ve updated my answer!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.