javastringrecursionsubstringcharat

Can someone explain this recursive Java method that reverses a string?


so I'm a junior in college trying to understand recursion. I understand the general concept but not how it's properly implemented. I found this extremely simple code and just can't seem to grasp how the last line (recursion) works. Any help and explanation would be awesome, thanks! (also finals coming up soon and boy am I nervous)

public static String reverse(String s) {
    if (s.isEmpty())
        return s;
    return reverse(s.substring(1)) + s.charAt(0);
}

Solution

  • Recursion process removing one by one char using substring , as substring take a beginning index which in 1 in you case so if our string is "ABC" then "ABC".substring(1) then substring will return "BC" So in your case reverse is processing with substring lets take our input is "abcd" for reverse methos

    then process will like with reverse method as a recursion

    bcd -> 1st reverse will call with this value
    cd -> then reverse will call with cd
    d -> then reverse will call with d
    "" -> then reverse will call with "" as its blank string so reverse will terminate
    

    once reverse method reach isEmpty statement the s.charAt(0) will start which will add at then end of return output from reverse method so it modified output like

    d
    dc
    dcb
    dcba
    

    so whole process will like:

    input to reverse method :bcd
    input to reverse method :cd
    input to reverse method :d
    input to reverse method : "" empty string
    result received from reverse method  
    After modified result with return value from reverse method and charAt(0) operation : d
    result received from reverse method  d
    After modified result with return value from reverse method and charAt(0) operation : dc
    result received from reverse method  dc
    After modified result with return value from reverse method and charAt(0) operation : dcb
    result received from reverse method  dcb
    After modified result with return value from reverse method and charAt(0) operation : dcba