The reverse method of the StringBuilder class is used to reverse the sequence of characters in a StringBuilder object. The original sequence is modified in-place, making it useful for dynamic string manipulation, palindrome checks, and efficient character sequence operations without creating new string objects.
class GFG {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello");
System.out.println("Original String: " + sb);
StringBuilder reversed = sb.reverse();
System.out.println("Reversed String: " + reversed);
}
}
Output
Original String: Hello Reversed String: olleH
Explanation: The original StringBuilder "Hello" is reversed in-place using reverse(), producing "olleH".
Syntax
public StringBuilder reverse()
- Returns: A StringBuilder object containing the reversed character sequence.
- Example: This code demonstrates reversing a StringBuilder using the reverse() method in Java.
Example: Reversing Words Using StringBuilder
public class GFG{
public static void main(String[] args) {
String sentence = "Java is powerful";
StringBuilder sb = new StringBuilder(sentence);
sb.reverse();
System.out.println(sb);
}
}
Output
String = WelcomeGeeks Reverse String = skeeGemocleW
Explanation: The program converts the given string into a StringBuilder object so it can be modified. The reverse() method reverses all characters in the sentence, and the result is printed to the console.