StringBuilder.reverse()
Reverses the contents of a StringBuilder.
Available since: Java 5
Syntax
public StringBuilder reverse()Return value
StringBuilderThe same StringBuilder, now reversed.
Examples
Reversing a string:
void main() {
String reversed = new StringBuilder("Java").reverse().toString();
IO.println(reversed);
}Output:
avaJA palindrome check:
void main() {
String word = "level";
boolean palindrome = new StringBuilder(word).reverse().toString().equals(word);
IO.println(palindrome);
}Output:
trueNotes
The method changes the object itself rather than creating a new one. Surrogate pairs (emoji) are reversed correctly, as single characters. String has no reverse() method of its own.
See also
- StringBuilder — A mutable string: useful when text is built piece by piece, especially in a loop.
- StringBuilder.toString() — Returns the contents of a StringBuilder as a regular String.
Related recipes
In the tutorial
- StringBuilder — StringBuilder in Java: a mutable string, append, insert, reverse, deleteCharAt, call chains and building a string in a loop.