So I am writing some recursive code for myself over spring break, without any purpose. Currently I am trying to make a recursive function that will reverse an inputted string from the user. I have this as of now, and it works.
import java.util.Scanner;
public class Recursion {
public static void main(String args[]) {
String userStr = " ", userAlt = " ";
int position = 0, length = userStr.length() - 1;
@SuppressWarnings("resource")
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a string.");
userStr = scan.nextLine();
userAlt = reverse(userStr);
System.out.println("\n" + userStr + " is... \n" + userAlt + " backwards!");
}
public static String reverse(String userStr) {
if(userStr.isEmpty()) {
return userStr;
}
else {
return reverse(userStr.substring(1)) + userStr.charAt(0);
}
}
}
Although, I am unsure how this return statement works because it is confusing me. I would think that the constant output would just be the first letter at the end of the string, without fully reversing it, but it works correctly in hindsight. I was hoping someone could help me, I do not think I am missing anything with the substring() method. Thanks in advance!
For example: if the inputted string was "spring" the output of userAlt would be "gnirps", as it should be. But why?
edit: Sorry about the useless code declarations of int position & length, I was working on a different way to solve it, came across this way then never deleted the code.