Reverse a String in Java: Methods and Examples

How-to basics · Updated November 22, 2026

Java does not have a built-in String.reverse() method. The standard direct solution is new StringBuilder(text).reverse().toString(), which returns a new string with its characters in reverse order.

Does Java Have a Direct String-Reversal Method?

No method on Java’s immutable String class reverses a string in place or returns a reversed string directly. In particular, code such as text.reverse() does not compile. The familiar method belongs to StringBuilder, a mutable sequence of characters, and StringBuffer, its synchronized counterpart.

This distinction explains the usual two-step expression: create a builder from the original string, reverse that builder, then convert the result back to a String. The original string is not modified. Java strings are immutable, so the result is a separate string value; the builder is simply a convenient temporary object for constructing it.

For most application code, use StringBuilder. It is the clearest standard-library option when one thread is working with the temporary value. You do not need a third-party library, a special import, or a loop for the everyday case.

The Standard StringBuilder Example

Here is a small method that reverses a non-null input:

public static String reverse(String text) {
    return new StringBuilder(text).reverse().toString();
}

For example, passing "Java" returns "avaJ". The expression runs in a clear sequence: the constructor copies the characters into a builder, reverse() changes their order in that builder, and toString() produces the result.

You can also write the steps separately if you want to inspect or reuse the builder:

String text = "Java";
StringBuilder builder = new StringBuilder(text);
builder.reverse();
String reversed = builder.toString();
System.out.println(reversed); // avaJ

StringBuilder.reverse() returns the builder itself, so method chaining is possible. The operation changes the builder rather than creating a reversed builder at each step. The final toString() call is what gives you an immutable String to return, store, or pass to another method.

What the Method Does and What It Costs

Reversal changes the sequence order: the first character becomes last, the second becomes next-to-last, and so on. The operation takes time proportional to the number of characters, commonly described as O(n), where n is the input length. The builder and returned string also require memory proportional to that length. That is normally a sensible trade-off for ordinary text processing.

The construction-and-reversal expression is useful because it is short without hiding an unusual algorithm. If the input is large and this operation is repeated in a performance-sensitive path, measure the real application before trying to optimize it. Avoid repeatedly concatenating one character at a time with immutable strings inside a loop: each concatenation may create another string, adding unnecessary work and temporary allocations. A builder is intended for this kind of mutable construction.

For an empty input, the result is an empty string. A one-character string is unchanged. Reversing a string twice returns the original sequence of characters, assuming the same reversal rules are used both times.

StringBuilder, StringBuffer, and Other Choices

StringBuilder and StringBuffer both provide a reverse() method. Their key practical difference is synchronization: StringBuffer synchronizes its methods, while StringBuilder does not. For a local builder used by one method, StringBuilder is generally the straightforward choice.

Synchronization on individual StringBuffer operations does not automatically make a larger sequence of operations on a shared object atomic. Nor is a shared mutable buffer automatically the best way to exchange text between threads. Choose a buffer based on the actual concurrency design, not simply because strings are involved. For a one-off reversal of an immutable string, there is usually no reason to prefer StringBuffer.

Other approaches can be useful when the requirement is different:

  • StringBuilder.reverse(): the normal choice for a concise reversal of a Java string.
  • A loop or two-pointer swap: helpful when learning the algorithm or when reversal is part of a larger transformation.
  • Code-point processing: appropriate when supplementary Unicode characters must be treated as individual code points.
  • Grapheme-cluster processing: needed when the goal is to reverse user-perceived characters, such as a letter together with its combining mark.

Writing a Reversal Loop Yourself

A manual loop can make the algorithm explicit. This version walks backward through the input and appends one Java char at a time:

public static String reverseWithLoop(String text) {
    StringBuilder result = new StringBuilder(text.length());
    for (int i = text.length() - 1; i >= 0; i--) {
        result.append(text.charAt(i));
    }
    return result.toString();
}

The capacity argument text.length() gives the result builder room for the input’s UTF-16 code units, avoiding repeated growth for this example. For ordinary basic Latin text, the output is what most people expect. However, the loop reverses individual UTF-16 code units. It can split the two units that encode a supplementary Unicode character, such as many emoji. The built-in builder method is preferable for general Java strings because it accounts for surrogate pairs.

A two-pointer implementation is another common educational option: convert the text to a mutable character array, swap the first and last positions, then move inward until the pointers meet. It has linear time complexity, but it has the same code-unit caveat unless it explicitly handles Unicode code points. More code does not automatically make an implementation more correct.

Unicode: Characters, Code Points, and Emoji

Java’s String stores text as UTF-16, so its length() counts UTF-16 code units, not necessarily the number of characters a person sees. A Unicode code point outside the Basic Multilingual Plane is represented using a pair of code units called a surrogate pair. The documented behavior of StringBuilder.reverse() keeps such pairs together while reversing the sequence.

That protection does not mean the method understands every visual character as a single indivisible unit. Some displayed characters consist of a base letter followed by one or more combining marks. Emoji can also be formed from multiple code points joined into a sequence. Reversing code points may separate those components, so the rendered result can look unexpected even when no surrogate pair was damaged.

If a task specifically requires reversing by Unicode code point rather than by UTF-16 unit, one approach is to collect the code points and append them backward:

public 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 treats each Unicode code point as a unit, including supplementary ones, but it still does not preserve every multi-code-point grapheme cluster. If the requirement is “reverse what a person perceives as each character,” define that requirement precisely and use grapheme-cluster segmentation rather than assuming that a Java char or code point always equals a displayed character.

Common Problems and Input Handling

The most frequent compile-time mistake is calling reverse() on a String. Create a StringBuilder first. Another common mistake is expecting the call to change the original string. It cannot: the builder is the mutable object, and the original String remains unchanged.

Null input needs an explicit policy. Passing null to new StringBuilder(text) throws a NullPointerException. That may be appropriate if null indicates a programming error. If your method should treat null as empty, state that behavior in code instead:

public static String reverseOrEmpty(String text) {
    if (text == null) {
        return "";
    }
    return new StringBuilder(text).reverse().toString();
}

Do not silently choose an empty-string result unless it fits the surrounding application’s contract; sometimes propagating the error or rejecting null is safer. Also consider whether the input can contain line breaks, spaces, or punctuation. The builder reverses the entire sequence, including those characters. If the request is to reverse words, preserve word order, or reverse only letters, that is a different transformation and requires a different algorithm.

Choosing the Right Method

For a typical interview exercise, utility method, or simple text transformation, use the builder expression and explain that it returns a new string. If the goal is to demonstrate loops, implement the algorithm yourself but mention its UTF-16 behavior. If input may contain non-BMP characters, the built-in reversal handles surrogate pairs; if the specification counts code points or grapheme clusters, choose an implementation that matches that unit instead.

A useful checklist is:

  • Is the input allowed to be null, and what should happen if it is?
  • Does “character” mean a UTF-16 unit, a Unicode code point, or a user-perceived grapheme?
  • Should spaces and punctuation reverse along with letters?
  • Is this a normal string operation, or is a custom algorithm genuinely required?

Answering those questions avoids the main source of confusion: the short Java method is easy, but the intended meaning of “reverse a string” can vary by application.

Frequently Asked Questions

What is the Java function to reverse a string?
Use new StringBuilder(text).reverse().toString(). Java’s String class has no reverse() method.

Can I use StringBuffer instead?
Yes. StringBuffer also has reverse(). It synchronizes its methods; for a local, single-threaded temporary builder, StringBuilder is usually the simpler choice.

Does reversing change the original string?
No. Java strings are immutable. Reversal changes a temporary builder and returns a new string value.

Does StringBuilder.reverse() work with emoji?
It keeps UTF-16 surrogate pairs together, which protects supplementary code points. Some emoji are multi-code-point sequences, however, so reversing can still change how a sequence displays.

How do I reverse a string without using reverse()?
Append characters from the final index down to zero, or swap elements from the ends of a mutable array inward. A simple char-based loop can split surrogate pairs, so account for Unicode if the input requires it.

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.