Reverse String in Java: Solution, Explanation & Practice
Reverse a string
Problem summary
Write a program that reverses any given string.
Starter code
public class Main {
public static void main(String[] args) {
String text = "Hello"; // Test case 1
// Reverse the string
// Print: Reversed: <result>
}
}Expected output and test cases
- Reverse Hello
Reversed: olleH
- Reverse Java
Reversed: avaJ
- Single character
Reversed: a
Hints
- Use StringBuilder's reverse() method
- Or iterate from end to start
- Build new string character by character
Validated solution
Reveal Java solution
public class Main {
static String reverse(String text) {
StringBuilder result = new StringBuilder(text.length());
for (int index = text.length() - 1; index >= 0; index--) result.append(text.charAt(index));
return result.toString();
}
public static void main(String[] args) {
System.out.println("Reversed: " + reverse("Hello"));
}
}How to approach the problem
Read characters from the final index down to zero and append them to one StringBuilder. The builder avoids creating a new immutable String after every character append.
Approach
- Allocate a builder with the known final length.
- Visit indices from length - 1 down to zero.
- Convert the builder once at the boundary.
Time and space complexity
Time: O(n). Space: O(n).
Edge cases to test
- An empty string stays empty.
- charAt works on UTF-16 code units; code-point-aware reversal is a different requirement.
Common mistakes
- Starting at text.length(), which is outside the valid index range.
- Repeatedly concatenating with + in a loop.
Follow-up challenge
Reverse Unicode code points without splitting an emoji surrogate pair.
Related Strings exercises
- Practice Check Contains in Java
- Practice Replace Characters in Java
- Practice String Palindrome in Java
Practice all Strings exercises · Run this idea in the Java compiler