How to reverse a string
Short answer
String has no reverse() method, but StringBuilder does:
void main() {
String reversed = new StringBuilder("Java").reverse().toString();
IO.println(reversed);
}Output:
avaJWith a loop
You can also build the string manually by walking the characters from the end:
void main() {
String text = "hello";
var result = new StringBuilder();
for (int i = text.length() - 1; i >= 0; i--) {
result.append(text.charAt(i));
}
IO.println(result);
}Output:
ollehReversing words
To reverse the order of words rather than letters, split the string and reverse the list:
void main() {
var words = new ArrayList<>(List.of("one two three".split(" ")));
Collections.reverse(words);
IO.println(String.join(" ", words));
}Output:
three two oneEmoji and rare characters
StringBuilder.reverse() handles characters made of two char values (surrogate pairs), such as most emoji, correctly. A manual loop over charAt() breaks them:
void main() {
String text = "ok👍";
IO.println(new StringBuilder(text).reverse());
IO.println(text.length());
}Output:
👍ko
4The length is 4 although you see three characters: the emoji takes two char values.
Common mistake
Expecting reverse() to change the original string. Strings in Java are immutable — you have to keep the result:
void main() {
String word = "abc";
new StringBuilder(word).reverse();
IO.println(word);
}Output:
abcFunctions used in this recipe
- StringBuilder.reverse() — Reverses the contents of a StringBuilder.
- String.charAt() — Returns the character at the given index.
- String.length() — Returns the number of characters in a string.