You say you want to know the most efficient way and you don't want to know some standard built-in way of doing this. Then I say to you: RTSL (read the source, luke):

Check out the source code for AbstractStringBuilder#reverse, which gets called by StringBuilder#reverse. I bet it does some stuff that you would not have considered for a robust reverse operation.

Answer from Tom on Stack Overflow
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ reverse-a-string-in-java
Reverse a String in Java - GeeksforGeeks
Explanation: Characters are stored in a list and reversed using Collections.reverse(). This approach is helpful when youโ€™re already working with Java collections. StringBuffer is similar to StringBuilder but thread-safe.
Published ย  October 14, 2025
๐ŸŒ
W3Schools
w3schools.com โ€บ java โ€บ java_howto_reverse_string.asp
Java How To Reverse a String
Java Wrapper Classes Java Generics Java Annotations Java RegEx Java Threads Java Lambda Java Advanced Sorting ... How Tos Add Two Numbers Swap Two Variables Even or Odd Number Reverse a Number Positive or Negative Square Root Area of Rectangle Celsius to Fahrenheit Sum of Digits Check Armstrong Num Random Number Count Words Count Vowels in a String Remove Vowels Count Digits in a String Reverse a String Palindrome Check Check Anagram Convert String to Array Remove Whitespace Count Character Frequency Sum of Array Elements Find Array Average Sort an Array Find Smallest Element Find Largest Element Second Largest Array Min and Max Array Merge Two Arrays Remove Duplicates Find Duplicates Shuffle an Array Factorial of a Number Fibonacci Sequence Find GCD Check Prime Number ArrayList Loop HashMap Loop Loop Through an Enum
๐ŸŒ
The Knowledge Academy
theknowledgeacademy.com โ€บ blog โ€บ reverse-a-string-in-java
How to Reverse a String in Java with Examples
To achieve this efficiently, you can use StringBuffer and StringBuilder. This method requires that you have a second string to XOR with, so you need to create a copy of the original string and reverse it first.
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ java string โ€บ how to reverse a string in java
How to Reverse a String in Java | Baeldung
January 8, 2024 - Weโ€™ll start to do this processing using plain Java solutions. Next, weโ€™ll have a look at the options that third-party libraries like Apache Commons provide. Furthermore, weโ€™ll demonstrate how to reverse the order of words in a sentence. We know that strings are immutable in Java.
๐ŸŒ
Simplilearn
simplilearn.com โ€บ home โ€บ resources โ€บ software development โ€บ how to reverse a string in java: 12 best methods
How to Reverse a String in Java: 12 Best Methods
May 5, 2025 - How to Reverse a String in Java? 1. Using toCharArray() 2. Using StringBuilder 3. Using While Loop/For Loop 4. Converting a String to Bytes 5. Using ArrayList
Address ย  5851 Legacy Circle, 6th Floor, Plano, TX 75024 United States
๐ŸŒ
Emeritus
emeritus.org โ€บ home โ€บ blog โ€บ information technology โ€บ 9 most convenient ways to reverse a string in java
9 Most Convenient Ways to Reverse a String in Java
September 24, 2024 - Next, the โ€˜Collections.reverse()โ€™ method reverses the character list. Lastly, the reversed character list converts back to a string using a StringBuilder class and another iterative for-each loop. ALSO READ: Here Are 5 Important Reasons to Learn Java Programming in 2024
Find elsewhere
๐ŸŒ
DevQA
devqa.io โ€บ reverse-string-java
Easiest Way to Reverse a String in Java
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class ReverseString { String reverse(String inputString) { String outString = ""; for(char c : inputString.toCharArray()) { outString = c + outString; } return outString; } @Test public void testAWord() { assertEquals("tobor", new ReverseString().reverse("robot")); } } import org.junit.jupiter.api.Test; import java.util.stream.Collectors; import java.util.stream.IntStream; import static org.junit.jupiter.api.Assertions.assertEquals; class ReverseString { String reverse(String inputString) { return IntStream.range(0, inputString.length()) .mapToObj(x-> inputString.charAt((inputString.length()-1) - x)) .map(character -> String.valueOf(character)) .collect(Collectors.joining("")); } @Test public void testAWord() { assertEquals("tobor", new ReverseString().reverse("robot")); } }
๐ŸŒ
Reddit
reddit.com โ€บ r/learnprogramming โ€บ how to reverse a string in java
r/learnprogramming on Reddit: how to reverse a string in java
April 4, 2021 -

hey guys i need your help in java so i have a very beginner problem and i'll probably be laughed at for asking this but how do you reverse a string in java

so far the online called I've been given to work with is:

import java.util.Scanner;
public class Program
{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String text = scanner.nextLine();
char[] arr = text.toCharArray();

//your code goes here

}
}

i don't know how to go about it, all i have to do is reverse the string. uhg it was so easy in python with just the (::-) is that how its written idk it's been some time python.

anyways i would appreciate any help and advice on learning java effectively i don't know much yet, i tried going on leetcode but daaaaamn it was crazy hard, i didn't manage to do any problem. thank you

๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ reverse a string in java
Reverse a String in Java - Scaler Topics
March 14, 2024 - The StringBuilder.reverse() method provides a straightforward way to reverse strings, making it an ideal choice for this operation. Reverse a string in Java can be efficiently done using a stack due to its Last-In-First-Out (LIFO) property.
๐ŸŒ
Codecademy
codecademy.com โ€บ docs โ€บ java โ€บ stringbuilder โ€บ .reverse()
Java | StringBuilder | .reverse() | Codecademy
August 22, 2022 - The .reverse() method returns a modified StringBuilder object with its character sequence rearranged in the opposite order. This is the most straightforward way to reverse a string in Java.
๐ŸŒ
Medium
javafullstackdev.medium.com โ€บ how-to-reverse-a-string-in-java-a-comprehensive-guide-b2720a975891
How to Reverse a String in Java: A Comprehensive Guide | by fullstackjavadev.in | Medium
June 7, 2024 - Reversing a string in Java can be accomplished in various ways, each with its own advantages and nuances. Whether you use the StringBuilder, a character array, recursion, or the Collections API, understanding these methods will enhance your ability to manipulate strings effectively in Java. Feel free to choose the method that best ...
๐ŸŒ
Hackr
hackr.io โ€บ home โ€บ articles โ€บ programming
How to Reverse a String in Java: 9 Ways with Examples [Easy]
January 30, 2025 - This tutorial covers 9 methods for how to reverse a string in Java, including methods using built-in reverse functions, recursion, and a third-party library.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ what-is-the-easiest-way-to-reverse-a-string-in-java
What is the easiest way to reverse a String in Java?
Built-in reverse() method The StringBuffer class provides you a method named reverse(). It reverses the contents of the current StringBuffer object and returns the resultant StringBuffer object. It is the easiest way to reverse a Sting using Java. To
๐ŸŒ
DZone
dzone.com โ€บ data engineering โ€บ data โ€บ the right way to reverse a string in java
The Right Way to Reverse a String in Java
December 6, 2018 - Usually, not writing code to solve problems is a good idea โ€” reverse a String using this simpler implementation than more common approaches.
๐ŸŒ
Javatpoint
javatpoint.com โ€บ how-to-reverse-string-in-java
How to Reverse String in Java - javatpoint
There are many ways to reverse String in Java. We can reverse String using StringBuffer, StringBuilder, iteration etc. Let's see the ways to reverse String in Java.
๐ŸŒ
Sololearn
sololearn.com โ€บ en โ€บ Discuss โ€บ 2805778 โ€บ how-to-reverse-a-string-in-java
How to reverse a string in java | Sololearn: Learn to code for FREE!
If you prefer not to use an array and keep it simple with just Strings, then: String myWord = "abc"; String reversed = ""; for (int i = myWord.length() - 1; i >= 0; i--) reversed += myWord.charAt(i); System.out.println(reversed);
๐ŸŒ
Medium
medium.com โ€บ @thurumerla.venkatesh โ€บ 5-ways-to-reverse-a-string-in-java-without-using-reverse-or-sort-methods-66bc995a5cc9
10 Different Ways to Reverse a String in Java (Without using reverse or sort methods) | by Thurumerla Venkatesh | Medium
February 19, 2024 - Here, weโ€™ll explore ten simple and basic approaches to reversing string using lambdas and streams, without relying on built-in methods like reverse or sort.
Top answer
1 of 4
36

Reversing a string, accurately and efficiently.

You are doing it accurately, yes. But, not very efficiently (although there are worse ways to do things).

NOTE:: Palacsint is right that you are not handling null input and surrogate-pairs in the input data. Your solution is not completely accurate. Consider this answer a discussion of the efficiency only.... though I have also updated this answer to include a solution which deals with surrogate pairs efficiently

To understand the efficiency side of things, you have to understand Java String internals.

  • Strings are immutable, cannot be changed.
  • Java is relatively slow at allocating/cleaning memory, try to avoid it.
  • Java can 'inline' method calls and make methods really fast.

So, the best way to make Java efficient is to create/use as little memory as possible, and still end up with a new String (instead of changing an existing string).

Your code has 1 string already, you are creating another string. You cannot avoid that.

What you can avoid though is what happens in between.

Your 'In Between'

What you are doing in between is a bit messy, and wasteful:

    char[] array = new char[s.length()];
    array = s.toCharArray();

You create a new array, then you throw it away, and replace it with the s.toCharArray()... why?

Could be just:

    char[] array = s.toCharArray();

Also, you have a loop that swaps the chars... this is implemented like:

for(int i=0; i<array.length/2; i++) {

This could be faster if you did it backwards ( could be - depending on which Java you use).

for (int i = array.length / 2; i >= 0; i--) {

This way it only has to do the array.length / 2 one time (though, as I say, some Java implementations will perhaps compile it to work out for you).

Finally, the charArrayToString() is serious overkill....

Converting to a StringBuilder then to a String is a waste of time/resources...

return charArrayToString(array);

can be

return new String(array);

EDIT: Also, as has been mentioned by Richard Miskin... and I assumed you were already using a StringBuilder .... StringBuilder is much more efficient in a single-thread situation than StringBuffer. Unless you have good reason, you always should use StringBuilder.

Efficient in-between ....

public String reverse(String s) {
    char[] array = s.toCharArray();
    char tmp;
    for(int i = (array.length - 1) / 2; i >= 0; i--) {
        tmp = array[i];
        array[i] = array[array.length-1-i];
        array[array.length-1-i] = tmp;
    }
    return new String(array);
}

Edit: a different way:

Here are some performance numbers...

String Reverse                           => 4473870 (hot 19.74881ms)
String Reverse Surrogate Aware           => 4473870 (hot 22.73488ms)
String Reverse B                         => 4473870 (hot 25.16192ms)
String Reverse StringBuilder             => 4473870 (hot 31.60709ms)
String Reverse StringBuilder NoNullCheck => 4473870 (hot 31.72952ms)
String Reverse Orig                      => 4473870 (hot 36.83827ms)

For each of those 'hot' runs, I am reversing the order of 479829 words (linux.words) (and there are 4473870 characters in the data excluding newlines).

  • the code I suggested above as the 'efficient in-between' does it in 20 milliseconds

  • based on the discussion about null and Surrogate Pairs, the following code does this 'right', and runs in 23 milliseconds:

    public String reverse(final String s) {
        if (s == null) {
            return null;
        }
        final char[] array = s.toCharArray();
        char tmp;
        for(int i=array.length/2; i >= 0; i--) {
            tmp = array[i];
            array[i] = array[array.length-1-i];
            array[array.length-1-i] = tmp;
        }
        //surrogate pairs will have been swapped.
        //identify, and un-swap them.
        for (int i = 1; i < array.length; i++) {
            if (Character.isHighSurrogate(array[i]) && Character.isLowSurrogate(array[i - 1])) {
                tmp = array[i];
                array[i] = array[i - 1];
                array[i - 1] = tmp;
            }
        }
        return new String(array);
    }
    
  • The following code does it in 25 milliseconds

    public String reverse(String s) {
        char[] array = new char[s.length()];
        for(int i=array.length - 1, j = 0; i >= 0; i--, j++) {
            array[i] = s.charAt(j);
        }
        return new String(array);
    }
    
  • @palacsint's recommendation does it in 31 milliseconds:

    public static String reverse(final String str) {
        if (str == null) {
            return null;
        }
        return new StringBuilder(str).reverse().toString();
    } 
    
  • @palacsint's recommendation (without the null-check) does it in 31 milliseconds:

    public static String reverse(final String str) {
        return new StringBuilder(str).reverse().toString();
    } 
    
  • Your code does it in 37milliseconds.

If you look at the code, my code creates three objects (char[] and new String() (which creates char[] as well))

The s.charAt() code also creates three objects, but has a lot of calls to String.charAt().

The @palacsint recommendation creates 4 objects (StringBuffer, StringBuffer's internal char[], String, and String's internal char[]);

That is true with and without the null-check.

Your code creates 5 objects (6 if you count the first array which is likely to be compiled out...) : (char[] array, new StringBuffer, StringBuffer's char[], String, and String's char[])

My guess is that there is a close correlation between our times simply because it takes 5ms to create 480,000 objects on the heap, plus some overhead of actual work.

2 of 4
17

Learn from the existing implementations, they usually have solutions to corner cases and common pitfalls. For example, Apache Commons Lang StringUtils also has a reverse function. Its implementation is quite simple:

public static String reverse(final String str) {
    if (str == null) {
        return null;
    }
    return new StringBuilder(str).reverse().toString();
} 

It uses StringBuilder.reverse whose javadoc mentions some special cases:

If there are any surrogate pairs included in the sequence, these are treated as single characters for the reverse operation. Thus, the order of the high-low surrogates is never reversed.

Here are a few tests:

@Test
public void testCstring() {
    assertEquals("\uD800\uDC00", CString.reverse("\uD800\uDC00")); // fails
    assertEquals("\uD800\uDC00", CString.reverse("\uDC00\uD800")); // OK
}

@Test
public void testStringUtils() throws Exception {
    assertEquals("\uD800\uDC00", StringUtils.reverse("\uD800\uDC00"));
    assertEquals("\uD800\uDC00", StringUtils.reverse("\uDC00\uD800"));
}

I don't know too much about these surrogates but you should check it and handle them in your code. I suppose the JDK's implementation is more reliable and it's not coincidence that the handle them in the way they mention in the javadoc.

There is a good question (with great answers) about surrogates on Stack Overflow: What is a surrogate pair in Java?

(See also: Effective Java, 2nd edition, Item 47: Know and use the libraries)