Google News
logo
Java Program to Reverse a String using Recursion
In the following example of Java program to reverse a string using recursion :
Program :
public class ReverseString {

    public static void main(String[] args) {
        String str = "Hello World";
        System.out.println(reverse(str));
    }

    public static String reverse(String str) {
        if (str.length() <= 1) {
            return str;
        } else {
            return reverse(str.substring(1)) + str.charAt(0);
        }
    }
}
Output :
dlroW olleH
In this program, we first declare a string variable str and initialize it with the value "Hello World". We then call the reverse method, passing in str, and print the returned value.

The reverse method is defined as a static method that takes a string parameter str and returns a string. The method uses recursion to reverse the string. If the length of the string is less than or equal to 1, it simply returns the string. Otherwise, it recursively calls itself with the substring of the original string starting from index 1, and concatenates the first character of the original string to the end of the reversed substring.

Ex 2: Program to reverse a string entered by user :

Program :
import java.util.Scanner;
public class JavaExample {

    public static void main(String[] args) {
        String str;
        System.out.println("Enter your username: ");
        Scanner scanner = new Scanner(System.in);
        str = scanner.nextLine();
        scanner.close();
        String reversed = reverseString(str);
        System.out.println("The reversed string is: " + reversed);
    }

    public static String reverseString(String str)
    {
        if (str.isEmpty())
            return str;
        //Calling Function Recursively
        return reverseString(str.substring(1)) + str.charAt(0);
    }
}
Output :
Enter your username: 
Free Time Learning
The reversed string is: gninraeL emiT eerF