Reverse a String using StringBuilder and StringBuffer in Java
This post will discuss how to reverse a string using StringBuilder and StringBuffer in Java.
The following example demonstrates how to use the StringBuilder.reverse() method to reverse a string in Java efficiently.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class Main { // Method to reverse a string in Java using `StringBuilder` public static String reverse(String str) { return new StringBuilder(str).reverse().toString(); } public static void main(String[] args) { String str = "Techie Delight"; // Note that string is immutable in Java str = reverse(str); System.out.println("The reversed string is " + str); } } |
Output:
The reversed string is thgileD eihceT
Alternatively, we can also use the StringBuffer.reverse() method. Using StringBuilder is suggested as it’s not synchronized and faster than StringBuffer.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class Main { // Method to reverse a string in Java using `StringBuffer` public static String reverse(String str) { return new StringBuffer(str).reverse().toString(); } public static void main(String[] args) { String str = "Techie Delight"; // Note that string is immutable in Java str = reverse(str); System.out.println("The reversed string is " + str); } } |
That’s all about reversing a String using StringBuilder and StringBuffer in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)