reverse string using recursion java with explanation

Solutions on MaxInterview for reverse string using recursion java with explanation by the best coders in the world

showing results for - "reverse string using recursion java with explanation"
Giulia
04 Feb 2016
1public static String reverse(String str) {
2    if ((null == str) || (str.length() <= 1)) {
3        return str;
4    }
5    return reverse(str.substring(1)) + str.charAt(0);
6}
Darwin
06 Jan 2018
1public class Test {
2
3    private static int i = 0;
4
5    public static void main(String args[]) {
6        reverse("Hello");
7    }
8
9    public static String reverse(String str) {
10        int localI = i++;
11        if ((null == str) || (str.length()  <= 1)) {
12            return str;
13        }
14        System.out.println("Step " + localI + ": " + str.substring(1) + " / " + str.charAt(0));
15        String reversed = reverse(str.substring(1)) + str.charAt(0);
16
17        System.out.println("Step " + localI + " returns: " + reversed);
18        return reversed;
19    }
20}