How to Reverse a String in Java? Total 7 different ways…

Last updated
App Shah
Crunchify » Interview Questions Answers » How to Reverse a String in Java? Total 7 different ways…

On Crunchify, we have published more than 500 Java Tutorials and in this tutorial we will go over steps on how to reverse a string in Java?

  • There are 7 different ways you can reverse a string in Java.

How to Reverse a String in Java? Total 7 different ways

package crunchify.com.tutorials;

import org.apache.commons.lang3.StringUtils;

import java.nio.charset.StandardCharsets;

/**
 * @author crunchify.com
 * How to Reverse a string in Java?
 * Version: 2.0
 */

public class CrunchifyReverseString {

    public static void main(String[] args) {
        String testString = "crunchify.com Example";
        System.out.println("String: " + testString);
        System.out.println("\nSolution1: Reverse Using reverseStringBuffer: " + reverseStringBuffer(testString));
        System.out.println("Solution2: Reverse Using reverseCharArray: " + reverseCharArray(testString));
        System.out.println("Solution3: Reverse Using reverseStringVariable: " + reverseStringVariable(testString));
        System.out.println("Solution4: Reverse Using reverseRecursion: " + reverseRecursion(testString));
        System.out.println("Solution5: Reverse Using BuilderReverse: " + StringBuilderReverse(testString));
        System.out.println("Solution6: Reverse Using reverseApacheCommonsLang3: " + reverseApacheCommonsLang3(testString));
        System.out.println("Solution7: Reverse Using reverseApacheCommonsLang3Separator: " + reverseApacheCommonsLang3Separator(testString));
    }

    // Solution1: Reverse using StringBuffer Example
    public static String reverseStringBuffer(String s) {

        // Causes this character sequence to be replaced by the reverse of the sequence.
		// If there are any surrogate pairs included in the sequence, these are treated as single characters for the reverse operation.
        return new StringBuffer(s).reverse().toString();
    }

    // Solution2: Reverse using Char Array Example
    public static String reverseCharArray(String s) {
        char[] reverseStringArray = new char[s.length()];
        for (int i = s.length() - 1, j = 0; i != -1; i--, j++) {
        	// Returns the char value at the specified index. An index ranges from 0 to length() - 1.
			// The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing.
            reverseStringArray[j] = s.charAt(i);
        }
        return new String(reverseStringArray);
    }

    // Solution3: Reverse using String Variable Example
    public static String reverseStringVariable(String s) {
        String reverseStringVariable = "";
        for (int i = s.length() - 1; i != -1; i--) {
            reverseStringVariable += s.charAt(i);
        }
        return reverseStringVariable;
    }

    // Solution4: Reverse using Recursion Example
    public static String reverseRecursion(String s) {
        if (s.length() <= 1) {
            return s;
        }
		// Returns a string that is a substring of this string.
		// The substring begins at the specified beginIndex and extends to the character at index endIndex - 1.
		return reverseRecursion(s.substring(1, s.length())) + s.charAt(0);
    }

    // Solution5: Reverse using StringBuilder(str).reverse()
    public static String StringBuilderReverse(String crunchifyString) {
        byte[] crunchifyValue = crunchifyString.getBytes(StandardCharsets.UTF_8);
        int length = crunchifyValue.length - 1;

        for (int crunchifyStart = (length - 1) >> 1; crunchifyStart >= 0; crunchifyStart--) {
            int crunchifyEnd = length - crunchifyStart;
            byte crunchifyTemp = crunchifyValue[crunchifyStart];
            crunchifyValue[crunchifyStart] = crunchifyValue[crunchifyEnd];
            crunchifyValue[crunchifyEnd] = crunchifyTemp;
        }
        return new String(crunchifyValue);

    }

    // Solution6: Reverse using Apache commons lang3
    public static String reverseApacheCommonsLang3(String s) {
        return (StringUtils.reverse("crunchify.com Tutorial"));

    }

    // Solution7: Reverse using Apache commons lang3
    public static String reverseApacheCommonsLang3Separator(String s) {
        return (StringUtils.reverseDelimited("crunchify.com Tutorial", ' '));
    }

}

Output:

/Library/Java/JavaVirtualMachines/jdk-14.0.2.jdk/Contents/Home/bin/java -javaagent:/Applications/IntelliJ IDEA.app/Contents/lib/idea_rt.jar=52056:/Applications/IntelliJ IDEA.app/Contents/bin -Dfile.encoding=UTF-8 -classpath /Users/appshah/crunchify/github/CrunchifyTutorials/target/classes
String: crunchify.com Example

Solution1: Reverse Using reverseStringBuffer: elpmaxE moc.yfihcnurC
Solution2: Reverse Using reverseCharArray: elpmaxE moc.yfihcnurC
Solution3: Reverse Using reverseStringVariable: elpmaxE moc.yfihcnurC
Solution4: Reverse Using reverseRecursion: elpmaxE moc.yfihcnurC
Solution5: Reverse Using BuilderReverse: elpmaxE moc.yfihcnurC
Solution6: Reverse Using reverseApacheCommonsLang3: lairotuT moc.yfihcnurC
Solution7: Reverse Using reverseApacheCommonsLang3Separator: Tutorial crunchify.com

Process finished with exit code 0

I look forward to hear about any different approaches that you’ve taken for solving this task.

4 thoughts on “How to Reverse a String in Java? Total 7 different ways…”

  1. Good example of reverse in Java – just thought to share that there could be a flavour where you need to reverese the sentence and not the words of the sentence. Recursion would be a great solution though there are other solution as well

    
    private static String reverseMe(String s) {  
      System.out.println("logger ::" + s);   
      int i = s.indexOf(" ");// getting the index of space which is delimeter in case of sentence  
      return i==-1 ? s : reverseMe(s.substring(i+1)) + " " + s.substring(0, i);  
        
     }  
    Reply

Leave a Comment