String Reverse Example using Iteration and Recursion in Java

String Reverse Example using Iteration and Recursion in Java

Here is code example String reverse using  iterative and recursive function written in Java. Recursive solution is just for demonstrative and education purpose, don’t use recursive solution in production code as it may result in StackOverFlowError if String to be reversed is very long String or if you have any bug in your reverse function, anyway its good test to make yourself comfortable with recursive functions in java.
import java.io.FileNotFoundException;
import java.io.IOException;
/**
*
*@author Javin
/
public class StringReverseExample {
    public static void main(String args[]) throws FileNotFoundException, IOException {
        //original string
        String str = “Sony is going to introduce Internet TV soon”;
        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) {
        //base case to handle one char string and empty string
        if (str.length() < 2) {
            return str;
        }
        return reverseRecursively(str.substring(1)) + str.charAt(0);
    }
}


How to convert comma separated String to ArrayList


List<String> list = new ArrayList<String>(Arrays.asList(string.split(" , ")));
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: