Reverse a String in Java Using Recursion – Step‑by‑Step Guide
Reverse a String in Java Using Recursion
Recursion is a powerful technique for solving problems that can be broken down into smaller, similar sub‑problems. Reversing a string is a classic example that demonstrates how a simple recursive function can elegantly handle string manipulation.
Why Use Recursion?
- Conceptual clarity – the function naturally mirrors the problem’s definition.
- Minimal code – only a few lines are needed to perform the reversal.
- Educational value – helps reinforce the base‑case / recursive‑step pattern.
Java Implementation
The following program reads a string, applies a recursive reversal method, and prints the result.
package com.guru99;
public class ReverseString {
public static void main(String[] args) {
String myStr = "Guru99";
String reversed = reverseString(myStr);
System.out.println("The reversed string is: " + reversed);
}
/**
* Recursively reverses the given string.
* @param str the string to reverse
* @return the reversed string
*/
public static String reverseString(String str) {
if (str.isEmpty()) {
return ""; // Base case: an empty string is its own reverse
}
// Recurse on the substring that excludes the first character
return reverseString(str.substring(1)) + str.charAt(0);
}
}
Typical Output
The reversed string is: 99uruG
Understanding the Flow
The recursion works by repeatedly stripping the first character and appending it to the result of the reverse of the remaining substring. When the substring becomes empty, the recursion unwinds, concatenating characters in reverse order.
Edge Cases & Performance
- Empty String – handled by the base case, returning an empty string immediately.
- Null Input – you can add a null‑check to avoid a {@code NullPointerException}.
- Time Complexity – O(n) for both time and space due to the recursion stack.
Takeaway
Recursive string reversal is concise and showcases core algorithmic thinking. For production code where performance is critical, an iterative approach or using a {@code StringBuilder} is preferable due to lower stack usage.
Java
- Mastering Java Strings: Creation, Methods, and Best Practices
- Java Recursion: Understanding, Examples, and Trade‑Offs
- Mastering String Representations in Java Enums
- Java String length() Method: How to Get a String’s Size (Example)
- Mastering Java's String compareTo() Method: Syntax, Use Cases, and Practical Examples
- Easily Convert Strings to Integers in Java: A Step‑by‑Step Guide
- Mastering Java's split() Method: A Practical Guide with Code Examples
- Converting a Char to a String in Java – Practical Examples and Best Practices
- Generate Fibonacci Sequence in Java: For, While, and Recursive Examples
- Java 8 Overview: New Functional, Streaming, and Date-Time APIs