-->

Hello,This is me!

ITEngineer8995

Professional Coder Coding is my passion

Tuesday, September 29, 2020

Java Program To Reverse a String using Recursion

  • September 29, 2020
  • by

 

Java Program To Reverse a String using Recursion

In this Java Program, we reverse a string using recursion.

The process in which the function calls itself directly or indirectly is called recursion and the corresponding function is called as recursive function

Logic :

 String reversed = reverseString(str);

Step 1 : Create obj str of String class and store the output string in it.

Step 2 : Create another object as reversed and apply the logic of the reverse string in it.

Step 3 : Output the reversed string using the System.out.println method.

Step 4 : Create reverseString method

Step 5 : Apply if statement, if str.isEmpty then return str.

Step 6 : Call function recursively.

Program :

public class JavaExample {

    public static void main(String []args)

    {

        String str = "Welcome To my Channel";

        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 :

The reversed string is : lennahC ym oT emocleW

For execution of the same do visit my YouTube Channel :

https://youtu.be/0XA6NlNoIQA




A blog full of codes of various languages like Java, .net, C, C++ etc with their outputs and some other IT stuff.

0 comments:

Post a Comment

ITEngineer8995
India

SEND ME A MESSAGE

Search This Blog

Powered by Blogger.

Pages