VOOZH about

URL: https://www.geeksforgeeks.org/java/conversion-between-string-stringbuilder-and-stringbuffer/

⇱ Conversion Between String, StringBuilder, and StringBuffer - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Conversion Between String, StringBuilder, and StringBuffer

Last Updated : 20 Feb, 2026

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.

Convert String to StringBuffer and StringBuilder

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.


Output
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.

Convert StringBuffer or StringBuilder to String

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. 


Output
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.

Convert StringBuffer to StringBuilder or vice-versa

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.


Output
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:

  • String objects are immutable; StringBuffer and StringBuilder are mutable.
  • StringBuffer is thread-safe (synchronized), whereas StringBuilder is faster but not thread-safe.
  • For single-threaded programs, prefer StringBuilder.
  • Conversions are mostly done via constructors or toString() method.
Comment