Write a java program to reverse a string using recursion. In this tutorial, I am going to explain how to write a java code which reverse an input string using recursion. I have also added the video at the end of this tutorial.
For example :
Input String: Object
Output String: tcejbO
In my previous posts, I have explained the difference between recursion and iteration. If you have a doubt about recursion then please check this post.
Binary search using recursion in Java
Java Program to Reverse a String using Recursion
In this code example, we write a function reverse which takes a string as an argument and reverses it recursively. The time complexity of this approach is O(n).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
/** * Reverse a String using Recursion */ public class ReverseString { //Method which reverse a string private static String reverse(String str) { //Terminating condition if(str == null || str.length() <= 1) { return str; } //Recursive function call return reverse(str.substring(1)) + str.charAt(0); } public static void main(String[] args) { String str = "Object"; String revStr = reverse(str); System.out.println(revStr); } } |
I have also explained how to reverse a string in java using recursion through video tutorial.