Program : String Reverse in Java using Recursion


String Reverse in Java 


Hello Friends, Today I will take you through a very interesting interview question. "How to Reverse a String in Java?

Don't be surprised if you are asked this question in many companies in your job interview, because as per my experience this one is the hot favorite of many interviewers.

So lets get down to see how we can reverse a string in Java



import java.io.FileNotFoundException;
import java.io.IOException;


public class DemoReverseAString{

    public static void main(String args[]) throws FileNotFoundException, IOException {

        //original string
        String str = "Software Testing An Easy Way";
        System.out.println("Original String: " + str);

        //reversed string using Stringbuffer
        String reverseStr = new StringBuffer(str).reverse().toString();
        System.out.println("Reverse String in Java using StringBuffer: " + reverseStr);

        //iterative method to reverse String in Java
        reverseStr = reverse(str);
        System.out.println("Reverse String in Java using Iteration: " + reverseStr);

        //recursive method to reverse String in Java
        reverseStr = reverseRecursively(str);
        System.out.println("Reverse String in Java using Recursion: " + reverseStr);

    }

    public static String reverse(String str) {
        StringBuilder strBuilder = new StringBuilder();
        char[] strChars = str.toCharArray();

        for (int i = strChars.length - 1; i >= 0; i--) {
            strBuilder.append(strChars[i]);
        }

        return strBuilder.toString();
    }

    public static String reverseRecursively(String str) {

        //handle one char string and empty string
        if (str.length() < 2) {
            return str;
        }

        return reverseRecursively(str.substring(1)) + str.charAt(0);

    }
}



That's all for now. We will go through some more interesting concepts in the next post. Keep watching this space for more updates !!