I am just learning how to use recursion now and I'm having a bit of trouble understand exactly how the following code is working:
public static String reverseString(String str)
{
if (str.length() == 0)
return str;
else
return reverseString(str.substring(1)) + str.charAt(0);
}
The goal of my program is to write a recursive method which will accept a String as an argument and return the reverse form of that String. I also know that this code DOES WORK.
I'm just a bit confused as to why it works. I was hoping someone who understands recursion and knows how to explain it! I understand how substring works and how the method is separating the first letter from the word (Ex. Mike ---> ike + M).
What I don't understand is how the base case ever reaches Zero and how the method returns the String in reverse order instead of just going through infinitely.
Any help would be greatly appreciated!
if (str.length() == 0)could beif (str.length() == 1)