To reverse a string in Java, wrap it in a StringBuilder, call reverse() and convert back: new StringBuilder(text).reverse().toString(). Java's String class has no reverse method of its own, so this one-liner is the standard answer, and the three other approaches below only make sense when you need to see the mechanics or avoid the builder.
public class ReverseDemo {
public static void main(String[] args) {
String text = "stressed";
String reversed = new StringBuilder(text).reverse().toString();
System.out.println(reversed);
}
}
Example output:
desserts
Why String has no reverse method
The Java documentation says strings are constant: their values cannot be changed after they are created. That is why text.reverse() does not exist and why no technique can flip a string in place. Each method below produces a new object and leaves the original alone, so the line text = reversed; is up to you if you want to replace the variable.
StringBuilder is the mutable counterpart. It holds a sequence of characters you can change, and its reverse() method replaces that sequence with its reverse. The method returns a reference to the same builder, which is what lets you chain .toString() straight after it. The documentation for toString() adds that a new String is allocated, and later changes to the builder do not affect it.
Method 1: StringBuilder.reverse()
Use this unless you have a reason not to. The constructor StringBuilder(String str) copies the string into the builder, reverse() flips it, and toString() hands back a normal String.
static String reverse(String text) {
return new StringBuilder(text).reverse().toString();
}
Passing null throws a NullPointerException, as the String documentation describes for null arguments in general. If your input can be null or empty, handle that before you call the method. An empty string simply comes back empty.
This is also the method that gets Unicode right. The StringBuilder documentation says that if the sequence contains surrogate pairs, they are treated as single characters for the reverse operation, so the order of the high and low surrogates is never reversed. The section on surrogate pairs below explains why that matters.
Method 2: loop over a char array
If you want to write the algorithm yourself, convert the string to a char array with toCharArray() and swap characters from both ends toward the middle. toCharArray() returns a new array, so changing it does not change the original string.
static String reverseWithLoop(String text) {
char[] chars = text.toCharArray();
int left = 0;
int right = chars.length - 1;
while (left < right) {
char held = chars[left];
chars[left] = chars[right];
chars[right] = held;
left++;
right--;
}
return new String(chars);
}
The loop stops when the two indexes meet, which handles odd and even lengths without a special case: for "abc" it swaps once and leaves the middle b alone. new String(char[]) copies the array, per the documentation. A for loop works just as well if you prefer it; see For Loop in Java for the syntax.
The weakness of this version is that it reverses char values, and a char is a 16-bit UTF-16 code unit, not always a whole character. For ordinary letters, digits and most text that makes no difference. For emoji and some rarer characters it breaks the string.
Method 3: recursion
A string reversed is its last part reversed, followed by its first character. Written recursively:
static String reverseRecursive(String text) {
if (text.length() <= 1) {
return text;
}
return reverseRecursive(text.substring(1)) + text.charAt(0);
}
The base case is a string of length 0 or 1, which is its own reverse. This version is good for teaching and interviews, but it is a poor choice in real code. Every call adds a stack frame, so a long enough string can end in a StackOverflowError, and every substring and + creates another new string. It also shares the char problem of Method 2, because charAt returns a single char, and for a surrogate it returns the surrogate value as-is.
Building the result by concatenating in a plain loop (result = text.charAt(i) + result) has the same cost: because strings are immutable, each step creates a new string.
Method 4: reverse by code point
If you want to reverse characters yourself and keep supplementary characters intact, work with code points instead of char values. String.codePoints() returns a stream of code point values, Character.toChars(int, char[], int) writes a code point into a char array and returns how many char values it used.
static String reverseByCodePoint(String text) {
int[] codePoints = text.codePoints().toArray();
char[] result = new char[text.length()];
int position = 0;
for (int index = codePoints.length - 1; index >= 0; index--) {
position += Character.toChars(codePoints[index], result, position);
}
return new String(result);
}
The result array is text.length() long because the reversed string contains the same char values, only regrouped. In practice this method duplicates what StringBuilder.reverse() already does, so reach for it only if you are already working with code point arrays.
Surrogate pairs: where reversing goes wrong
Java stores text as UTF-16. The Character documentation explains that characters above U+FFFF are called supplementary characters and are represented as a pair of char values: a high surrogate (\uD800 to \uDBFF) followed by a low surrogate (\uDC00 to \uDFFF). The String documentation notes that index values refer to char code units, so a supplementary character uses two positions. The emoji U+1F600 is one such character: its two char values are 馃榾.
Reverse those two values one by one and the low surrogate lands in front of the high one, which is not a valid pair. This program compares Method 1 with Method 2 on the string "a", the emoji and "b", written with escapes so the source file encoding does not matter:
String text = "a馃榾b";
System.out.println(text.length()); // 4 char values
System.out.println(text.codePointCount(0, text.length())); // 3 code points
System.out.println(new StringBuilder(text).reverse()); // b, emoji, a
System.out.println(reverseWithLoop(text)); // broken
Expected behavior, based on the documentation: length() returns 4 while codePointCount returns 3. The StringBuilder line prints the emoji intact between b and a. The loop version produces \uDE00\uD83D in the middle, an unpaired low surrogate followed by an unpaired high surrogate, which a terminal typically shows as question marks or replacement characters depending on its encoding.
One limit remains for every method here. They reverse code points, not what a reader sees as one character. A letter followed by a separate combining accent is two code points, and reversing moves the accent in front of the wrong letter. The Java documentation for these classes works at the code point level, so handling such text needs a different approach than the ones shown here.
Which method to use
| Method | Handles emoji | Best for |
|---|---|---|
StringBuilder.reverse() | Yes | Almost all real code |
| char array swap loop | No | Learning, ASCII-only data |
| Recursion | No | Teaching, interviews; not long strings |
| Code point array | Yes | When you already hold code points |
Check for a palindrome
A common use of reversing is the palindrome test. Reverse the string and compare it with the original:
static boolean isPalindrome(String text) {
return text.equals(new StringBuilder(text).reverse().toString());
}
Use equals() here. The == operator compares object references, so it would report false even for identical text held in two different objects. Decide up front whether case and spaces count: "Level" is not a palindrome as written, but text.toLowerCase() first would make it one.
Frequently asked questions
- Does Java have a built-in String.reverse() method?
- No. The String class has no reverse method because strings are immutable. The standard way to reverse a string in Java is to wrap it in a StringBuilder, call reverse() on that, and convert the result back with toString().
- Why can't I reverse a String in place?
- The Java documentation states that String values cannot be changed after they are created. Every reversal technique therefore builds a new object, either a StringBuilder, a char array, or a new String, and leaves the original string untouched.
- Does StringBuilder.reverse() work correctly with emoji?
- Yes. Its documentation says surrogate pairs in the sequence are treated as single characters, so the high and low surrogate of an emoji or other supplementary character are never swapped. A hand-written loop over char values does not have this protection.
- Is the reversed string the same as the original for a palindrome?
- Yes. A palindrome reads the same in both directions, so you can test one by reversing the string and comparing the result to the original with equals(). Compare with equals(), not ==, because == compares object references.