➤ Sum of digits in a String
➤ Count No of Vowels String
➤ String Pattern Programs in Java
➤ Take String Input In Java
➤ Take Multiple String Input in Java
➤ How To Reverse a String In Java
➤ Remove Special Characters
➤ String – Remove Character
➤ String Palindrome In Java
➤ Sort String In Java
➤ How to Compare Strings In Java
➤ Second Occurrence of Character
➤ Replace nth Occurrence String
➤ Last Occurrence of Character
➤ Uppercase & Lowercase
➤ Java Check If Char is Uppercase
➤ Check If String is Uppercase
➤ Swap Characters in String Java
➤ Java String indexOf() Method
➤ How to Replace Dot in Java?
➤ How to Find Length of String
➤ Substring Method In Java
➤ Split Method In Java
Reverse a String In Java Using Recursion | Recursion is a technique to divide the problem into smaller components so that we can solve the problem easily. Previously we have seen different approaches to reverse a string in Java programming. Now, we will see how to reverse a string in Java using recursion.
Program to Reverse a String In Java Using Recursion
public class Main {
public static void reverseString(String string) {
if ((string == null) || (string.length() <= 1))
System.out.println(string);
else {
System.out.print(string.charAt(string.length() - 1));
reverseString(string.substring(0, string.length() - 1));
}
}
public static void main(String[] args) {
String string = "Hello World!";
System.out.println("String: " + string);
System.out.print("String after reverse: ");
reverseString(string);
}
}
Output:-
String: Hello World!
String after reverse: !dlroW olleH
We have defined a reverseString() method which uses the recursion technique to display the reverse of a string in Java. In this method, first, we find out the length of the given string. If the string length is 0 or less than 0 then we just print the string, else we will reverse the string and print it on the output screen.
For recursive calls internally it is using the substring() method and removes the last character from the input string. In the main function, we take a string and call reverseString() method recursively to reverse the string.
If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!