Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (9.5k points)

Below is my Java code to reverse a string recursively:

public static String reverse(String str) {

    if ((null == str) || (str.length() <= 1)) {

        return str;

    }

    return reverse(str.substring(1)) + str.charAt(0);

}

Can anyone give me an explanation of how it works?

1 Answer

0 votes
by (19.7k points)

When you call the function, it takes the 1st character ‘ str.charAt(0)’ of the string and places it at the end. Then it calls the  itself - reverse() - on the remainder - str.substring(1). When you add it together, you get the result reverse(str.substring(1)) + str.charAt(0)

When the passed String has one character or less with no remainder left (str.length()  <= 1), then it stops calling itself recursively to return the passed string. 

See the below implementation to understand how it works:

reverse("Hello")

(reverse("ello")) + "H"

((reverse("llo")) + "e") + "H"

(((reverse("lo")) + "l") + "e") + "H"

((((reverse("o")) + "l") + "l") + "e") + "H"

(((("o") + "l") + "l") + "e") + "H"

"olleH"

Interested in Java? Check out this Java Certification by Intellipaat.  

Related questions

0 votes
1 answer
asked May 15, 2021 in Java by sheela_singh (9.5k points)
0 votes
1 answer
asked Feb 19, 2021 in Java by Jake (7k points)
0 votes
1 answer
asked Mar 4, 2021 in Java by RohitSingh (2.6k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...