![]() |
VOOZH | about |
In Java, String, StringBuilder, and StringBuffer are used to handle text data, but they differ in mutability and thread safety. Understanding how to convert between them is important for performance optimization and clean coding practices.
A String is immutable, meaning its content cannot be changed after creation. To perform modifications (like appending or reversing), convert it into a mutable object, such as a StringBuffer or StringBuilder.
skeeG GeeksforGeeks
Explanation: The above example shows how to convert a String into StringBuffer and StringBuilder. We are reversing the String using StringBuffer and then adds more text using StringBuilder.
To convert StringBuffer or StringBuilder to String, use the toString() method. This method creates a new String object containing the same sequence of characters. Changes to the original StringBuffer or StringBuilder do not affect the String.
StringBuffer to String: Geeks StringBuilder to String: Hello GeeksForGeeks Geeks
Explanation: The above example shows how to convert StringBuffer and StringBuilder objects into String with the help of toString() method.
There is no direct conversion between StringBuffer and StringBuilder. You can achieve this by first converting to a String and then to the other class using its constructor.
Geek
Explanation: The above example shows how to convert a StringBuffer into a String and then converting the same String into a StringBuilder.
Important points: