How to Reverse a String in Java
The Challenge
Reverse a string - turn "Hello" into "olleH"!
Solutions
Method 1: Using StringBuilder
String text = "Hello World";
String reversed = new StringBuilder(text).reverse().toString();
System.out.println("Original: " + text);
System.out.println("Reversed: " + reversed);
// Output: Original: Hello World
// Reversed: dlroW olleHMethod 2: Using Loop
String text = "Hello World";
String reversed = "";
for (int i = text.length() - 1; i >= 0; i--) {
reversed += text.charAt(i);
}
System.out.println("Reversed: " + reversed);
// Output: Reversed: dlroW olleHMethod 3: Using char Array
String text = "Hello World";
char[] chars = text.toCharArray();
int left = 0, right = chars.length - 1;
while (left < right) {
char temp = chars[left];
chars[left] = chars[right];
chars[right] = temp;
left++;
right--;
}
String reversed = new String(chars);
System.out.println("Reversed: " + reversed);
// Output: Reversed: dlroW olleHMethod 4: Using Recursion
public static String reverse(String str) {
if (str.isEmpty()) {
return str;
}
return reverse(str.substring(1)) + str.charAt(0);
}
// Usage
System.out.println(reverse("Hello")); // olleHDid You Know?
The StringBuilder.reverse() method is the most efficient way to reverse a string in Java. It modifies the string in-place with O(n) time complexity!
Watch Out!
Using string concatenation in a loop (reversed += char) is inefficient because strings are immutable. Each concatenation creates a new string object!
Real-World Use Cases
- Palindrome checking: Compare string with its reverse
- Data processing: Reverse order of data
- Text effects: Create mirror text
- Algorithms: String manipulation challenges
›Short versionOpen if you only have a minute.
- new StringBuilder(text).reverse().toString() reverses UTF-16 char values.
- A character outside the basic multilingual plane is two chars. Reversing those chars breaks the pair.
- Building the reverse with += is O(n^2). The builder is linear.
- Null has no reverse. Decide that at the boundary.
Reverse a string
Produce a string with the char sequence in the opposite order.
Working approach
- Use StringBuilder.reverse for ordinary BMP text.
- Use a builder in a backward loop when you want the loop to be visible.
- Do not reverse char by char if the text contains characters that need surrogate pairs.
Walk the sample
- Input "code"
- Chars from the end are e, d, o, c
- The result is "edoc"
The trap
reverse() swaps char values, not visible characters. An emoji stored as a surrogate pair comes out with the two halves exchanged.
static String reverseBmp(String text) {
return new StringBuilder(text).reverse().toString();
}
// A manual loop has the same char-level behavior:
static String reverseByHand(String text) {
StringBuilder out = new StringBuilder(text.length());
for (int i = text.length() - 1; i >= 0; i--) {
out.append(text.charAt(i));
}
return out.toString();
}What does StringBuilder.reverse do to a single emoji?
The emoji is one code point stored as two chars, a high surrogate and a low surrogate.
reverse swaps those chars. The result is not a well-formed copy of that character. For text that stays inside one char per character, the builder reverse is the right one-liner.
Time O(n), space O(n).
Easy to get wrong
- Appending with += in the backward loop.
- Assuming one char is one character the reader sees.