reverse
- Java course
- Beginner
- Lesson 91/116
- 4 min
Learn to reverse text with reverse.
reverse: flipping text
The reverse method flips the text inside a StringBuilder. It takes no parameter; it changes the same object in place.
StringBuilder sb = new StringBuilder("Java");
sb.reverse();
// "avaJ"One common use is palindrome (equals its reverse) checking. You compare the original text with the reversed version to see if they are equal. Example palindrome words: radar, level.
Palindrome check with reverse
To check whether a word is a palindrome, you reverse it with a StringBuilder and compare it to the original.
String word = "kayak";
String reversed = new StringBuilder(word)
.reverse().toString();
boolean isPalindrome = word.equals(reversed);
// trueHere the chain new StringBuilder(word).reverse().toString() produces the reversed text in one line. Then we compare with equals. This approach is short and readable.
Practice Reverse the word
Start a StringBuilder with "Hello". Reverse it with reverse and print the result with toString.
Starter code
public class Main {
public static void main(String[] args) {
// Start the StringBuilder with "Hello"
// Reverse with reverse
// Print the result with toString
}
}Sample solution
StringBuilder sb = new StringBuilder("Hello");
sb.reverse();
System.out.println(sb.toString());Expected output
olleH
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the reverse() method return?
- The same StringBuilder object
- A new String
- void
- A new StringBuilder Correct answer
Explanation: reverse returns the builder itself; it changes in place.
2 Match input to reversed output
| Term | Meaning |
|---|---|
"Java" |
"avaJ" |
"kayak" |
"kayak" |
"ab" |
"ba" |
"x" |
"x" |
3 Fill in the blank: reverse
StringBuilder sb = new StringBuilder("Java");
sb.____();
System.out.println(sb);
StringBuilder sb = new StringBuilder("Java");
sb.reverse();
System.out.println(sb);
Explanation: sb.reverse() flips the text.