String Reversal Using Recursion in java

Write a Java program to reverse a Sring using recursion. there are many methods and logic to reverse a string in Java. In this tutorial, let’s see String Reversal Using Recursion in java

The agenda is to reverse a string using recursion.

Example:-

Input :- Hello

Output:- olleH

Algorithm for String Reversal Using Recursion in Java

 1. First take the input string from the user. 

2. Create a method reverse() that takes input string as an argument.

3. The method will remove the first character from the string and places it at the end of the string.

It uses two methods:-

  • substring() method returns the new string that is a substring of the given string.
  • charAt() method returns the character at a specified index of string.

4. Thus, the input string will go on decreasing. If it becomes empty, it means that the entire string is reversed.

Java Program for String Reversal Using Recursion

import java.util.Scanner;
public class StringReversal
{
    public static String reverse(String s)
    {
        if(s.isEmpty()) return s;
        else return reverse(s.substring(1))+s.charAt(0);
    }
    public static void main(String[] args)
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter a string:");
        String s=sc.nextLine();
        String rev=reverse(s);
        System.out.println("The reversed string is:"+rev);
    }
}

Output for String Reversal Program Using Recursion:-

}