Reverse String Recursion Java – Reverse a String in Java

In this simple Java tutorial, we will learn- How to Reverse a String using Recursion in Java? First, We will start with understanding the Recursion, and Later, we will see- How to Reverse a string with and without Recursion in Java. You will also learn, what is happening behind the Reversing a String in Java program. So, Let’s get started –

Learn How to Print Reverse of string with or without using Recursion in Java


Some prior knowledge – Reverse string recursion Java

Before starting the implementation on developing the Java program, you should have at least heard about these Core Java Concepts

  • Loops (for/while)
  • String class in Java,
  • Use of String methods such as- split(), substring(), charAt() etc,
  • The Recursion technique,

However, If you don’t have a better understanding of any of the above concepts, Don’t worry, as we’ll learn everything in this Core Java tutorial. But, first, let’s understand – What is Recursion and How can we use it to Reverse any String in Java.


Quick notes on Recursion

Recursion is actually a different methodology of solving simple to complex problems. By the way, We have previously learned about it in our Fibonacci Recursion – Java Guide to generate a Fibonacci series using Recursion. And, here are some it’s valuable points that you should be aware of –

What is Fibonacci sequence - Wikipedia
Src : Wikipedia
  • Recursion is a technique to solve a problem in self – similar manner.
  • Technically speaking, a method or function that calls itself is known as Recursive method.
  • The process of a method to call itself, again and again, is known as Recursion.

But, before going further with Reverse string recursion Java, first, Let’s see- Is it possible to Reverse a String without using Recursion in Java?


1) Reverse a String WITHOUT using Recursion in Java

It is completely possible to Reverse a String without using recursion in Java and there are multiple ways of doing it. One of the simplest ways to Reverse a String “without” using Recursion in Java is by invoking reverse() method of StringBuilder class.

You may get surprised or already know that the java.lang.String class does NOT have any in-built reverse() method. You can use the StringBuilder class for reverse() in Java.

Here’s a simple example of reverse() method of java.lang.StringBuilder class –

package com.shubhamklogic.java.file.io;

// Java program to Reverse a String using StringBuilder class

class ReverseStringSolution1 {                               // Explaining : Step-by-Step

    public static void main(String[] args) {

        String yourInputString = "Java - ShubhamKLogic.com";

        // Object of StringBuilder by passing 'yourInputString'
        StringBuilder theStringBuilder = new StringBuilder(yourInputString);

        // Reversing 'yourInputString' using 'theStringBuilder'
        theStringBuilder = theStringBuilder.reverse();

        // printing yourInputString after reverse
        System.out.println(theStringBuilder.toString());
    }
}

 

Result :

We have passed the String object containing value yourInputString = “Java – ShubhamKLogic.com“; And, As you’ll run the above Java program, you’ll successfully get the following Reversed string output :

moc.cigoLKmahbuhS - avaJ

2) Reverse a String WITH Recursion in Java

Here is a simple program to Reverse a String using Recursion in Java –

package com.shubhamklogic.java.recursion;

public class ReverseStringSolution2 {                                     // Explaining: Step-by-Step

    private static short counter;                                                  // Optional Statement: We are using it for Counting Purposes... 

    public static void main(String[] args) {

        String yourInputString = "Java - ShubhamKLogic";     // Your string: to be Reversed

        // Our custom Method that takes String and returns its reverse
        String reversed = reverseTheString(yourInputString);

        System.out.println("REVERSED: String is = " + reversed);
    }


    // Our method - It is taking String parameter > then processes it > and then returns the Reversed string
    public static String reverseTheString(String yourInputString) {


        if (yourInputString.isEmpty()) {
            System.out.println("FOUND   : Empty String");
            return yourInputString;
        }


        // Incrementing the counter, 
        // As we are going to call reverseTheString(...) again
        counter++;
        System.out.println( counter + ") String for further processing in Recursion : " + yourInputString.substring(1));


        // Recursion: Calling again to Itself
        return reverseTheString( yourInputString.substring(1) ) + yourInputString.charAt( 0 );
    }
}

 

Output:

As you’ll run the above Java program, you’ll successfully get the following results –

1) String for further processing in Recursion : ava - ShubhamKLogic
2) String for further processing in Recursion : va - ShubhamKLogic
3) String for further processing in Recursion : a - ShubhamKLogic
4) String for further processing in Recursion :  - ShubhamKLogic
5) String for further processing in Recursion : - ShubhamKLogic
6) String for further processing in Recursion :  ShubhamKLogic
7) String for further processing in Recursion : ShubhamKLogic
8) String for further processing in Recursion : hubhamKLogic
9) String for further processing in Recursion : ubhamKLogic
10) String for further processing in Recursion : bhamKLogic
11) String for further processing in Recursion : hamKLogic
12) String for further processing in Recursion : amKLogic
13) String for further processing in Recursion : mKLogic
14) String for further processing in Recursion : KLogic
15) String for further processing in Recursion : Logic
16) String for further processing in Recursion : ogic
17) String for further processing in Recursion : gic
18) String for further processing in Recursion : ic
19) String for further processing in Recursion : c
20) String for further processing in Recursion :
FOUND: Empty String
REVERSED: String is = cigoLKmahbuhS - avaJ

Logic – Behind the code

Here’s, what is Happening in above Java program to Reverse String using Recursion –

INPUT: "Java - ShubhamKLogic"

reverseTheString("Java - ShubhamKLogic")
(reverseTheString("ava - ShubhamKLogic")) + "J"
((reverseTheString("va - ShubhamKLogic")) + "a") + "J"
(((reverseTheString("a - ShubhamKLogic")) + "v") + "a") + "J"
((((reverseTheString(" - ShubhamKLogic")) + "a") + "v") + "a") + "J"
...
...
...

OUTPUT: "cigoLKmahbuhS - avaJ"
  • As you can verify above, we had a string “Java – ShubhamKLogic”;
  • We passed the string to our reverseTheString(…) method.
  • Then, it computed the reverse of this string by calling reverseTheString(…) method Recursively.
  • The method splitted the string using substring( ) and charAt( );
  • We recursively added or concatenated the substrings from index 1 to end, with the first character.
  • As per the counter, the method called itself 20 times.
  • And, we have successfully got our the desired Reversed String using Recursion in Java.

 

Wrap Up 

So far, we have learned, How to Reverse String using Recursion in Java. We have also seen How to Reverse a String without using Recursion in Java. We understood, the Logic used behind our Reverse String – Recursion Java Solution.

I hope, this article helped you to learn a bit more about Java Recursion and String Manipulations concepts. If you have any doubt or query, then do comment or send me a direct mail via Google, I’ll try my best to give you the solution within a day.

Also, Rate this article on Facebook and, Don’t forget to check Other Useful Java Articles that you may like :

Read Next :

Leave a Comment