0
0
JavaProgramBeginner · 2 min read

Java Program to Reverse String Using Recursion

You can reverse a string in Java using recursion by defining a method like reverse(String str) that returns str.charAt(str.length() - 1) + reverse(str.substring(0, str.length() - 1)) until the string is empty.
📋

Examples

Inputhello
Outputolleh
InputJava
OutputavaJ
Input
Output
🧠

How to Think About It

To reverse a string using recursion, think of taking the last character and adding it to the reverse of the rest of the string. Keep doing this until the string is empty, which is the base case to stop recursion.
📐

Algorithm

1
Check if the string is empty; if yes, return empty string.
2
Take the last character of the string.
3
Call the reverse function recursively on the substring excluding the last character.
4
Concatenate the last character to the result of the recursive call.
5
Return the concatenated string.
💻

Code

java
public class ReverseString {
    public static String reverse(String str) {
        if (str.isEmpty()) {
            return "";
        }
        return str.charAt(str.length() - 1) + reverse(str.substring(0, str.length() - 1));
    }

    public static void main(String[] args) {
        String input = "hello";
        System.out.println(reverse(input));
    }
}
Output
olleh
🔍

Dry Run

Let's trace the input "hello" through the recursive reverse method.

1

Initial call

reverse("hello") takes last char 'o' and calls reverse("hell")

2

Second call

reverse("hell") takes last char 'l' and calls reverse("hel")

3

Third call

reverse("hel") takes last char 'l' and calls reverse("he")

4

Fourth call

reverse("he") takes last char 'e' and calls reverse("h")

5

Fifth call

reverse("h") takes last char 'h' and calls reverse("")

6

Base case

reverse("") returns empty string ""

7

Unwinding recursion

Each call returns last char + result: 'h' + "" = "h", then 'e' + "h" = "eh", then 'l' + "eh" = "leh", then 'l' + "leh" = "lleh", then 'o' + "lleh" = "olleh"

CallInput StringLast CharRecursive CallReturn Value
1hellooreverse("hell")olleh
2helllreverse("hel")lleh
3hellreverse("he")leh
4heereverse("h")eh
5hhreverse("")h
6
💡

Why This Works

Step 1: Base Case

The recursion stops when the string is empty, returning an empty string with if (str.isEmpty()) return "";.

Step 2: Recursive Step

Each call takes the last character using str.charAt(str.length() - 1) and adds it to the reversed substring.

Step 3: Building Result

By concatenating the last character to the reversed substring, the string is reversed step by step as recursion unwinds.

🔄

Alternative Approaches

Using StringBuilder and recursion
java
public class ReverseString {
    public static String reverse(String str) {
        return reverseHelper(str, str.length() - 1, new StringBuilder());
    }

    private static String reverseHelper(String str, int index, StringBuilder sb) {
        if (index < 0) {
            return sb.toString();
        }
        sb.append(str.charAt(index));
        return reverseHelper(str, index - 1, sb);
    }

    public static void main(String[] args) {
        System.out.println(reverse("hello"));
    }
}
This approach uses a helper method with a StringBuilder to avoid creating many string objects, improving performance.
Using iterative approach
java
public class ReverseString {
    public static String reverse(String str) {
        StringBuilder sb = new StringBuilder();
        for (int i = str.length() - 1; i >= 0; i--) {
            sb.append(str.charAt(i));
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(reverse("hello"));
    }
}
This method uses a loop instead of recursion, which is simpler and more efficient for large strings.

Complexity: O(n) time, O(n) space

Time Complexity

The function calls itself once per character, so it runs in linear time proportional to the string length.

Space Complexity

Each recursive call adds a layer to the call stack, so space used is proportional to the string length.

Which Approach is Fastest?

The iterative approach is fastest and uses less memory, while recursion is elegant but uses more stack space.

ApproachTimeSpaceBest For
RecursionO(n)O(n)Learning recursion and small strings
Recursion with StringBuilderO(n)O(n)Better performance with recursion
IterativeO(n)O(1)Large strings and performance
💡
Always define a clear base case in recursion to avoid infinite calls.
⚠️
Beginners often forget the base case, causing the program to crash with a stack overflow error.