Java String Reverse: Methods and Examples

How-to basics · Updated November 22, 2026

Java’s String class has no built-in reverse() method. For ordinary text, the standard solution is to create a StringBuilder, call its reverse() method, and convert the result back to a string: new StringBuilder(text).reverse().toString().

Why String Has No reverse() Method

Java strings are immutable: once a String object has been created, its contents cannot be changed. Methods that appear to modify a string, such as replace() or toLowerCase(), return a result rather than altering the original object. Reversing text follows the same principle: the operation must produce a reversed value, not edit the existing string in place.

The Java library provides reverse() on the mutable StringBuilder class instead. A builder is intended for constructing or changing character sequences. You can pass a string to its constructor, reverse the builder, and then obtain a new immutable string. This division is useful: String is a safe, convenient value type for text, while StringBuilder is a tool for operations that change text during a calculation.

There is also a StringBuffer class with a reverse() method. It is synchronized for thread-safe access to its individual operations, but that does not usually make it the best choice for a local reversal. For routine single-threaded code, use StringBuilder.

The Simplest Way to Reverse a String

For a non-null string, the common one-line solution is:

String text = "Java";
String reversed = new StringBuilder(text).reverse().toString();

System.out.println(reversed); // avaJ

The constructor copies the characters from text into a builder. The call to reverse() changes the builder’s sequence and returns that same builder, so toString() creates the resulting String. The original variable still refers to "Java"; it has not been changed.

For reusable code, put the operation in a method and decide how it should handle null. One reasonable policy is to reject it explicitly:

static String reverse(String text) {
    if (text == null) {
        throw new IllegalArgumentException("text must not be null");
    }
    return new StringBuilder(text).reverse().toString();
}

Another API might intentionally return null when given null, or use an annotation or a type that makes nullability explicit. The important point is that StringBuilder cannot be constructed from a null string; without a deliberate policy, the call will fail with a NullPointerException.

What the Reverse Operation Does

Conceptually, reversal takes the sequence of text units and places them in the opposite order. For simple English letters and digits, that description matches what most people expect: "cat" becomes "tac", and "12345" becomes "54321". Spaces and punctuation are reversed too. For example, "Java is fun" becomes "nuf si avaJ"; reversal does not preserve word order or sentence structure.

StringBuilder.reverse() operates on Java’s UTF-16 representation, with special handling so a valid surrogate pair remains in the correct high-surrogate/low-surrogate order when it is reversed. This matters because a single Unicode code point outside the Basic Multilingual Plane is represented by two Java char values. The method is therefore safer for such characters than a simple loop that swaps individual char values.

That handling does not mean reversal understands every visual character a reader sees. A displayed symbol can consist of multiple code points, such as a base letter followed by a combining accent, or an emoji sequence joined with a zero-width joiner. Reversing those code points can separate or reorder their components. The distinction between UTF-16 units, Unicode code points, and user-perceived characters is important whenever text can contain more than basic Latin letters.

Manual Reversal and Code-Point-Aware Reversal

A loop that swaps the first and last char, then moves inward, is a common exercise. It works for basic ASCII text, but it can split a surrogate pair. That makes it unsuitable as a general Unicode replacement for StringBuilder.reverse(). Manual code is useful when learning algorithms or when the problem specifically defines its input as ASCII; otherwise, prefer the library method.

If the requirement is to reverse Unicode code points, rather than UTF-16 units, you can read code points into an array and append them in reverse order:

static String reverseCodePoints(String text) {
    int[] points = text.codePoints().toArray();
    StringBuilder result = new StringBuilder(text.length());

    for (int i = points.length - 1; i >= 0; i--) {
        result.appendCodePoint(points[i]);
    }
    return result.toString();
}

This example uses APIs available in modern Java, including Java 8 and later. It preserves each code point as a unit, but it still does not necessarily keep a visible grapheme intact. For example, a combining mark may be a separate code point from the letter it accents. If the product requirement is to reverse what a person perceives as individual characters, define that requirement precisely and use a Unicode library with grapheme-cluster support rather than assuming that a code point equals a displayed character.

Choosing the Right Approach

The best method depends on what “character” means in the task. For typical programming exercises and strings containing ordinary letters, digits, and punctuation, StringBuilder is concise and clear. For text where supplementary Unicode characters must remain intact, it also handles surrogate pairs. If the specification explicitly requires code-point order, use a code-point-based implementation and document that choice.

  • Ordinary string reversal: Use new StringBuilder(text).reverse().toString().
  • Learning an in-place algorithm: A character-array or two-pointer solution can demonstrate the logic, but state whether the input is restricted to ASCII or another defined range.
  • Reverse Unicode code points: Iterate through text.codePoints() in reverse, for example by collecting the code points into an array.
  • Reverse visible grapheme clusters: Use a library and a clearly specified Unicode segmentation rule; neither a simple char loop nor code-point reversal guarantees this behavior.

Do not choose an elaborate algorithm just because it appears more optimized. The standard builder call communicates intent, avoids common indexing errors, and is usually the most maintainable option.

Common Mistakes and Misconceptions

A frequent compile-time mistake is writing text.reverse(). There is no such instance method on String. Call reverse() on a StringBuilder or StringBuffer instead. Another common error is expecting the original string variable to change after reversal. Since strings are immutable, assign the returned result to a variable if it needs to be used later.

Also avoid treating a string as though it were an array. Java does not allow expressions such as text[i]; use charAt(i) to read a UTF-16 code unit, or convert to an array if the algorithm genuinely requires one. A hand-written loop using charAt() can be correct for an explicitly limited character set, but it is not automatically correct for all Unicode text.

Reversal is not the same as reversing words. To turn "one two" into "two one" while keeping each word intact, split or tokenize the text and reverse the word sequence; reversing the whole string produces "owt eno". Similarly, reversing a palindrome check’s input is only one part of that problem: decisions about case, spaces, punctuation, and Unicode normalization must be made separately.

Finally, a reversed string is not necessarily meaningful in the language or format of the original. Reversing a path, URL, structured identifier, or natural-language sentence can produce a value that is syntactically or semantically invalid. Reverse text only when the application’s requirements call for it.

Performance and Memory Considerations

Creating a builder from a string and then converting it back produces a new result, so reversal requires storage proportional to the input length. That is generally appropriate because the original string is immutable and must remain available if other code refers to it. Reversing an existing StringBuilder changes that builder’s contents and can avoid creating an additional builder, but it does not change the behavior of any strings previously produced from it.

If a program repeatedly constructs output by adding one character at a time, use a builder for the construction rather than repeatedly concatenating strings inside a loop. Repeated concatenation can create many intermediate strings. For a single reversal, however, the direct constructor-and-reverse expression is already clear; replacing it with a custom loop is rarely justified unless profiling or a precise requirement demonstrates a need.

Capacity can matter when building very large text, but the result still needs space for the characters. A builder initialized from a string is sized from that input, so ordinary reversal does not require a guessed capacity. In most applications, correctness, Unicode expectations, and readable code matter more than micro-optimizing this operation.

Frequently Asked Questions

Does Java String have a reverse() method?

No. String does not provide reverse(). Use new StringBuilder(text).reverse().toString() to get a reversed string.

Does reversing a StringBuilder change the original String?

No. A string used to create the builder remains unchanged because strings are immutable. The builder’s own character sequence is reversed, and toString() returns a string containing that result.

How do I reverse a string without StringBuilder?

You can copy its characters into an array and swap values from the ends inward, then create a new string from the array. That approach needs careful bounds and Unicode handling. If you use it, define whether the input is ASCII, UTF-16 code units, or Unicode code points; for everyday use, StringBuilder is simpler.

Does StringBuilder.reverse() work with emojis?

It preserves valid UTF-16 surrogate pairs, which lets many supplementary emoji code points remain valid. But some displayed emoji are sequences of multiple code points, and reversing those components can change how they appear. Code-point safety is not the same as grapheme-cluster safety.

How can I reverse the order of words instead?

Separate the text into words according to the whitespace rules your application needs, reverse the word list, and join it again. This differs from reversing every character in the entire string, and basic splitting may not preserve repeated spaces or punctuation exactly.

Related

Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.

More in How-to basics

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.