In this tutorial you will learn about the Java Program to Reverse a String using Recursion and its application with practical example.
Java Program to Reverse a String using Recursion
In this tutorial, we will learn to create a Java program that will reverse a string Using Recursion in Java programming.
Prerequisites
Before starting with this tutorial, we assume that you are the best aware of the following Java programming topics:
- Operators in Java Programming.
- Usage of Conditional statements in Java Programming.
- Basic Input and Output function in Java Programming.
- Basic Java programming.
What is Recursion? Reverse a Sentence Using it?
The recursion means a function or program that repeats itself until the condition is satisfied. The recursion repeats the program execution in a controlled format. Today we will reverse a sentence using the recursion.
Algorithm:-
1 2 3 4 5 6 7 8 9 |
1. Declaring the variables for the program. 2. Taking the input string from the user. 3. Send that string to the function. 4. Passing those variable to if conditional. 5. Printing the result words. |
In this program of recursion, we will take the input string from the user and store it in the string variable. Then will use that string variable in a user-defined function. At last, we will reverse that string using a recursion program.
With the help of the below, code, we will reverse a string Using Recursion.
Program Code:-
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 27 28 29 30 31 32 33 34 35 |
//Java Program to reverse a string using recursion. public class RevStr//Reversing the string using the function { //recursive function to reverse a string public String reverseString(String str) { //checks if the string is empty if(str.isEmpty()) { //printing the output string to the user. System.out.println("First the String is empty.") ; //if the above condition is true returns the same string return str; } else { //printing the output string to the user. return reverseString(str.substring(1))+str.charAt(0); } } public static void main(String[] args) { RevStr rs = new RevStr(); //Declaring the variables for the program. String resultantSting1 = rs.reverseString("W3Adda"); String resultantSting2 = rs.reverseString("Tutorials"); String resultantSting3 = rs.reverseString("Rocks"); //Calling the reverse string function. System.out.println(resultantSting1); //Calling the reverse string function. System.out.println(resultantSting2); //Calling the reverse string function. System.out.println(resultantSting3); } } |
Output:-
In the above program, we have first initialized the required variable.
- ResultantString1 = it will hold the string value for the program.
- ResultantString2 = it will hold the string value for the program.
- ResultantString3 = it will hold the string value for the program.
Calling the reverse string function.
Body of the Reverse string function.
Printing the output of the program reversed string.