Reverse a String with Recursion in Java

In this post, we will see how to reverse a string with recursion in Java.

 
As seen in the previous post, we can easily reverse a string in Java using stack data structure. As stack is involved, we can easily convert the code to use recursion call stack. As String is immutable, we first convert the given String into character array, then reverse the character array and finally convert the character array back into the string.

 

Download   Run Code

Output:

Reversed string is: !em esreveR

 
Above solution uses a static variable which is not recommended. We can easily solve this problem without using any static variable.

 

Download   Run Code

Output:

Reversed string is: !em esreveR

 

Using substring() function

We can also use String.substring(int, int) method to recursively reverse a string in Java. Below code uses String.charAt(int) method to isolate the first or last character of the String and recurse for remaining string using substring().

 

Approach #1

 

Download   Run Code

Output:

Reversed string is: !em esreveR

 

Approach #2

 

Download   Run Code

Output:

Reversed string is: !em esreveR

 
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)

Loading...

Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂
 


Leave a Reply

avatar
  Subscribe  
Notify of