This tutorial will show you how we can reverse a string in Java. We have different ways to reverse a string in Java and I have presented here in three ways how to reverse a string.

Using reverse() method in StringBuffer

public String usingStringBufferReverse(String string) {
        if (string == null || string.isEmpty()) {
            return string;
        }
        String reverseString = new StringBuffer(string).reverse().toString();
        return reverseString;
    }

 

Using reverse() method in StringBuilder

public String usingStringBuilderReverse(String string) {
        if (string == null || string.isEmpty()) {
            return string;
        }
        String reverseString = new StringBuffer(string).reverse().toString();
        return reverseString;
    }

 

Using custom reverse method

public String usingCustomReverse(String string) {
        if (string == null || string.isEmpty()) {
            return string;
        }
        String reverse = "";
        for (int i = string.length() - 1; i >= 0; i--) {
            reverse = reverse + string.charAt(i);
        }
        return reverse;
    }

 

Using recursion

public String usingRecursion(String string) {
        if (string == null || string.isEmpty() || string.length() < 2) {
            return string;
        }
        return usingRecursion(string.substring(1)) + string.charAt(0);
    }

 

Testing

public static void main(String[] args) {
        StringReverse sr = new StringReverse();

        String word = "HelloWorld";

        //quick wasy to reverse String in Java - Use StringBuffer       
        String reverse = sr.usingStringBufferReverse(word);
        System.out.printf(" original String : %s , reversed String : %s  %n", word, reverse);

        //another quick to reverse String in Java - use StringBuilder
        reverse = sr.usingStringBuilderReverse(word);
        System.out.printf(" original String : %s , reversed String : %s %n", word, reverse);

        //one way to reverse String using custom method
        reverse = sr.usingCustomReverse(word);
        System.out.printf(" original String : %s , reversed String : %s %n", word, reverse);

        //reverse String using recursion
        reverse = sr.usingRecursion(word);
        System.out.printf(" original String : %s , reversed String : %s %n", word, reverse);
    }

 

Thanks for your reading. Please leave a comment.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on Roy Tutorials | TwitterFacebook Google PlusLinkedin | Reddit | Email Me

Leave a Reply

Your email address will not be published. Required fields are marked *