How to Reverse a String in Java using Recursion

In this 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.

Write a Java Program to Reverse String

  1. package com.guru99;
  2. public class ReverseString {
  3. public static void main(String[] args) {
  4. String myStr = "Guru99";
  5. //create Method and pass and input parameter string
  6. String reversed = reverseString(myStr);
  7. System.out.println("The reversed string is: " + reversed);
  8. }
  9. //Method take string parameter and check string is empty or not
  10. public static String reverseString(String myStr)
  11. {
  12. if (myStr.isEmpty()){
  13. System.out.println("String in now Empty");
  14. return myStr;
  15. }
  16. //Calling Function Recursively
  17. System.out.println("String to be passed in Recursive Function: "+myStr.substring(1));
  18. return reverseString(myStr.substring(1)) + myStr.charAt(0);
  19. }
  20. }

Output:

String to be passed in Recursive Function: uru99
String to be passed in Recursive Function: ru99
String to be passed in Recursive Function: u99
String to be passed in Recursive Function: 99
String to be passed in Recursive Function: 9
String to be passed in Recursive Function: 
String in now Empty
The reversed string is: 99uruG

No comments:

Post a Comment