In this example program, we will reverse a string entered by a user.
We will create a function to reverse a string. Later we will call it recursively until all characters are reversed.
import java.util.*;
public class Reverse_String
{
public static void main(String[] args)
{
String myStr = "";
Scanner sc=new Scanner(System.in);
System.out.println("Enter the string to reverse");
myStr=sc.nextLine();
//create Method and pass and input parameter string
String reversed = reverseString(myStr);
System.out.println("The reversed string is: " + reversed);
}
//Method take string parameter and check string is empty or not
public static String reverseString(String myStr)
{
if (myStr.isEmpty()){
System.out.println("String in now Empty");
return myStr;
}
//Calling Function Recursively
System.out.println("String to be passed in Recursive Function: "+myStr.substring(1));
return reverseString(myStr.substring(1)) + myStr.charAt(0);
}
}
public class Reverse_String
{
public static void main(String[] args)
{
String myStr = "";
Scanner sc=new Scanner(System.in);
System.out.println("Enter the string to reverse");
myStr=sc.nextLine();
//create Method and pass and input parameter string
String reversed = reverseString(myStr);
System.out.println("The reversed string is: " + reversed);
}
//Method take string parameter and check string is empty or not
public static String reverseString(String myStr)
{
if (myStr.isEmpty()){
System.out.println("String in now Empty");
return myStr;
}
//Calling Function Recursively
System.out.println("String to be passed in Recursive Function: "+myStr.substring(1));
return reverseString(myStr.substring(1)) + myStr.charAt(0);
}
}
Output:
Enter the string to reverse
arce11mm
String to be passed in Recursive Function: rce11mm
String to be passed in Recursive Function: ce11mm
String to be passed in Recursive Function: e11mm
String to be passed in Recursive Function: 11mm
String to be passed in Recursive Function: 1mm
String to be passed in Recursive Function: mm
String to be passed in Recursive Function: m
String to be passed in Recursive Function:
String in now Empty
The reversed string is: mm11ecra
String to be passed in Recursive Function: ce11mm
String to be passed in Recursive Function: e11mm
String to be passed in Recursive Function: 11mm
String to be passed in Recursive Function: 1mm
String to be passed in Recursive Function: mm
String to be passed in Recursive Function: m
String to be passed in Recursive Function:
String in now Empty
The reversed string is: mm11ecra