Learn how to reverse a string in Java using StringBuilder, StringBuffer, and iteration with complete examples, code, output, and explanations.
Code Explanation (Step-by-Step) :
Reverse String Using StringBuffer
- Creates a String variable str and stores the value “hello world”.
- new StringBuffer(str) creates a StringBuffer object containing “hello world”.
- reverse() method reverses all characters in the string.
- toString() method converts the StringBuffer object back to a String.
- The reversed string is stored in the variable s1.
Reverse String Using StringBuilder
- new StringBuilder(str) creates a StringBuilder object containing “hello world”.
- reverse() method reverses all characters in the string.
- toString() method converts the StringBuilder object back to a String.
- The reversed string is stored in the variable s2.
Reverse String Using Iteration
- Now Calls the reverseTest() method and passes “hello world” as an argument.
- Creates an empty StringBuilder object to store the reversed characters.
- toCharArray() converts the string “hello world” into a character array.
- The for loop starts from the last index and iterates up to index 0.
- append(c[i]) appends each character to the StringBuilder in reverse order.
- toString() converts the StringBuilder object to a String.
- The reversed string is returned to the calling method.
public class StringReverse {
public static void main(String[] args) {
String str = "hello world";
String s1 = new StringBuffer(str).reverse().toString();
System.out.println("From StringBuffer reverse: " + s1);
String s2 = new StringBuilder(str).reverse().toString();
System.out.println("From StringBuilder reverse: " + s2);
System.out.println("From iteration method reverse: " + reverseTest(str));
}
public static String reverseTest(String str) {
StringBuilder sb = new StringBuilder();
char[] c = str.toCharArray();
for (int i = c.length - 1; i >= 0; i--) {
sb.append(c[i]);
}
return sb.toString();
}
}
Output :-
From StringBuffer reverse:- dlrow olleh
From StringBuilder reverse:- dlrow olleh
From iteration method reverse:- dlrow olleh
Difference Between StringBuilder and StringBuffer in Java
Both StringBuilder and StringBuffer are used to create mutable strings in Java and both provide methods like append(), insert(), delete(), and reverse().
StringBuilder
- It is not synchronized.
- Faster because it does not provide thread safety.
- Recommended for single-threaded applications.
- Uses less overhead than StringBuffer.
StringBuffer
- It is synchronized and thread-safe.
- It is multiple threads can access it safely.
- It is slightly slower because of synchronization overhead.
- It is suitable for multi-threaded environments.
Which One Should We Use?
- Use StringBuilder when thread safety is not required because it provides better performance.
- Use StringBuffer when multiple threads are modifying the same string object and thread safety is required.