How To Reverse A String In Java: Explained
Reversing a string is one of the most common beginner exercises in Java, and it's also a frequent interview question because there are several different approaches, each demonstrating a different Java concept.
Method 1: Using StringBuilder
The simplest and most efficient approach uses the built-in reverse() method of the StringBuilder class.
String str = "Uncodemy";
String reversed = new StringBuilder(str).reverse().toString();
System.out.println(reversed); // ymedocnU
Method 2: Using a Character Array
Convert the string into a character array, then swap characters from both ends toward the middle.
char[] chars = str.toCharArray();
int left = 0, right = chars.length - 1;
while (left < right) {
char temp = chars[left];
chars[left] = chars[right];
chars[right] = temp;
left++;
right--;
}
System.out.println(new String(chars));
Method 3: Using a for Loop
Build a new string by appending characters starting from the end of the original string.
String result = "";
for (int i = str.length() - 1; i >= 0; i--) {
result += str.charAt(i);
}
System.out.println(result);
Method 4: Using Recursion
A recursive approach reverses the rest of the string first, then appends the first character at the end.
static String reverseRecursive(String s) {
if (s.isEmpty()) {
return s;
}
return reverseRecursive(s.substring(1)) + s.charAt(0);
}
Which Method Should You Use?
StringBuilder.reverse()— best for real-world code, fastest and cleanest- Character array swap — good for understanding how reversal works internally
- for loop with concatenation — simple but inefficient for long strings
- Recursion — useful for learning recursive thinking, but less efficient than iterative methods
StringBuilder.reverse() — manual loop-based string concatenation creates many unnecessary intermediate String objects.Master Java with Uncodemy
Hands-on training, live projects, and placement support in our Java Programming Course.
The Two-Pointer Swap Written Out in Full
The character array method is the one interviewers most often ask you to write on a whiteboard, because it shows you can reverse data in place without a helper class. Here is a complete, reusable version:
public static String reverseWithArray(String input) {
if (input == null || input.length() < 2) {
return input; // nothing to reverse
}
char[] chars = input.toCharArray();
int left = 0, right = chars.length - 1;
while (left < right) {
char temp = chars[left];
chars[left] = chars[right];
chars[right] = temp;
left++;
right--;
}
return new String(chars);
}
Trace it with "java": swap positions 0 and 3 to get "aavj", then 1 and 2 to get "avaj". The pointers cross and the loop ends. Only half the characters are visited, though the time is still linear.
Comparing Cost and Behaviour
| Method | Time | Extra space | Notes |
|---|---|---|---|
| StringBuilder.reverse() | O(n) | O(n) | Handles surrogate pairs correctly |
| Char array swap | O(n) | O(n) for the array | Splits surrogate pairs |
| Loop with += | O(n²) in practice | Many temporary strings | Avoid for long text |
| Recursion with substring | O(n²) | O(n) call stack | Very long input can cause StackOverflowError |
The loop with += looks linear, but each concatenation copies the whole string built so far, so the total work grows with the square of the length.
Unicode: The Detail That Impresses Interviewers
A Java char is a 16-bit unit. Characters such as many emoji are stored as two char values called a surrogate pair. Swapping single chars reverses the two halves and produces broken output. StringBuilder.reverse() is documented to keep surrogate pairs together, which is one more reason to prefer it.
Even so, some visible characters are built from several code points, such as a letter plus a combining accent or certain emoji with skin-tone modifiers. Reversing those correctly needs grapheme-aware handling, for example with java.text.BreakIterator. Mentioning this limit shows real depth.
Related Problems Built on the Same Idea
- Palindrome check: compare a string with its reverse, or move two pointers inward and stop at the first mismatch, which avoids building a new string.
- Reverse the words, not the letters: split on spaces and join in reverse order.
- Reverse only letters: skip digits and symbols with the two-pointer method.
String sentence = "learn java step by step";
String[] words = sentence.trim().split("\\s+");
java.util.Collections.reverse(java.util.Arrays.asList(words));
System.out.println(String.join(" ", words)); // step by step java learn
In an interview, start with the StringBuilder answer, then offer the two-pointer version when asked to avoid library methods. Finish by stating time and space complexity without being prompted.
Common mistakes: forgetting the null check, using <= in the while condition (harmless but wasteful), and comparing strings with == instead of equals() in palindrome checks.