In this post, we will see a Java program to reverse a string using recursion. Also learn to reverse string without recursion as well.
Read More: Reverse words in a string in Java
1. Reverse String using recursion
To reverse a string by characters, we can write a recursive function which will perform following actions –
- Take first character and append to last of string
- Perform above operation until string ends
public class StringExample { public static void main(String[] args) { String blogName = "How To Do In Java "; String reverseString = reverseString(blogName); System.out.println(reverseString); } public static String reverseString(String string) { if (string.isEmpty()){ return string; } //Calling function recursively return reverseString(string.substring(1)) + string.charAt(0); } }
Program output.
avaJ nI oD oT woH
2. Reverse a sentence in Java – without recursion
You can reverse a string by character easily, using a StringBuilder.reverse() method.
public class StringExample { public static void main(String[] args) { String blogName = "How To Do In Java"; String reverseString = new StringBuilder(string).reverse(); System.out.println(reverseString); } }
Program output.
avaJ nI oD oT woH
In this example, you learned to reverse a string using recursive function and also without using recursive function as well.
Happy Learning !!
Was this post helpful?
Let us know if you liked the post. That’s the only way we can improve.
abc
Hey!
There is a problem with “Reverse a sentence -without recursion”.
There are casting errors.Why don’t you give it a try?
nehan
yes, there is casting error. I did it this way and it worked
public class test
{
public static void main(String[] args)
{
String blogName = “How To Do In Java”;
StringBuilder reverseString = new StringBuilder(blogName).reverse();
System.out.println(reverseString);
}
}