Skip to content

Java Convert String to StringBuilder – StringBuilder to String example (StringBuffer)

This Java example shows how to convert String to StringBuilder and StringBuilder to String in Java. The example also shows how to convert String to StringBuffer and StringBuffer to String in java.

How to convert String to StringBuilder or StringBuffer?

There are many reasons you may want to convert String to StringBuilder or StringBuffer in Java. Since the String is immutable (that means you cannot change the content of the string once it is created), you may want to convert it to mutable StringBuilder or StringBuffer if you want to append multiple values to it.

The StringBuilder class provides a constructor that accepts String. You can use that constructor to convert String to StringBuilder object.

This constructor creates a new StringBuilder object having the same characters as the specified parameter String.

Similarly, we can use the constructor of the StringBuffer class to convert String to StringBuffer as given below.

This constructor creates a new StringBuffer object with the same content as the parameter String.

Example

Output

Note: The capacity of the newly created StringBuilder or StringBuffer object will be 16 + the length of the String object.

How to convert StringBuilder to String (StringBuffer to String)?

It’s fairly easy. We can use the toString method of the StringBuilder or StringBuffer class to convert StringBuilder or StringBuffer to a String object.

Example

Output

You may also want to visit the Java conversion tutorial to learn more about other conversions in Java.

This example is a part of the Java StringBuffer tutorial and Java StringBuilder tutorial.

References:
StringBuilder JavaDoc
StringBuffer JavaDoc

About the author

Leave a Reply

Your email address will not be published.