Ora

How to Convert a StringBuffer to String in Java?

Published in Java String Conversion 4 mins read

To convert a StringBuffer to a String in Java, the most straightforward and universally used method is to simply call the toString() method on the StringBuffer object.

This method effectively creates a new String object, taking a snapshot of the StringBuffer's current character sequence and initializing the new String with it. Subsequent modifications to the original StringBuffer object will not impact the content of the String object that was previously returned by toString().

Understanding the StringBuffer.toString() Method

The toString() method provided by the StringBuffer class is specifically designed for this conversion. When invoked, it performs the following:

  1. Creates a New String Object: A brand-new java.lang.String object is instantiated in memory.
  2. Copies Character Sequence: The current sequence of characters held by the StringBuffer object is copied into this newly created String object.
  3. Returns the String: The newly created and populated String object is then returned.

This process ensures that the String object is an independent, immutable representation of the StringBuffer's content at the time of conversion.

Syntax

public String toString()

The method takes no arguments and returns a String object.

Practical Example

Here's a simple Java example demonstrating how to convert a StringBuffer to a String:

public class StringBufferToStringConversion {
    public static void main(String[] args) {
        // 1. Create a StringBuffer object
        StringBuffer myStringBuffer = new StringBuffer();

        // 2. Append some characters to the StringBuffer
        myStringBuffer.append("Hello");
        myStringBuffer.append(" ");
        myStringBuffer.append("Java!");

        // 3. Convert the StringBuffer to a String using toString()
        String myString = myStringBuffer.toString();

        // 4. Print the resulting String
        System.out.println("Converted String: " + myString); // Output: Converted String: Hello Java!

        // 5. Demonstrate immutability: modify StringBuffer after conversion
        myStringBuffer.append(" Welcome.");
        System.out.println("Modified StringBuffer: " + myStringBuffer); // Output: Modified StringBuffer: Hello Java! Welcome.
        System.out.println("Original String (unchanged): " + myString); // Output: Original String (unchanged): Hello Java!
    }
}

As seen in the example, even after myStringBuffer is modified, myString retains its original content, highlighting the immutability of String objects and the snapshot nature of the toString() conversion.

Why Use StringBuffer?

While String is immutable, StringBuffer (and its non-synchronized counterpart, StringBuilder) are designed for mutable sequences of characters. This makes them ideal for scenarios where you need to build or modify strings frequently, as it avoids the overhead of creating many intermediate String objects.

  • Thread-Safety: StringBuffer is thread-safe because its methods are synchronized. This means it can be safely used in multi-threaded environments where multiple threads might access or modify the same string buffer simultaneously without data corruption.
  • Performance: For single-threaded operations, StringBuilder is generally preferred over StringBuffer due to its better performance (it doesn't incur the overhead of synchronization). However, their toString() methods function identically.

When to Convert?

Typically, you would convert a StringBuffer to a String when:

  • You have finished building the string and no further modifications are expected.
  • You need to use the string in a context that requires an immutable String object (e.g., as a map key, in String manipulation methods, or for passing to methods expecting String arguments).

StringBuffer vs. StringBuilder vs. String

It's helpful to understand the distinctions between these classes:

Feature String StringBuilder StringBuffer
Mutability Immutable Mutable Mutable
Thread-Safety Inherently thread-safe Not thread-safe Thread-safe
Performance Good for constant strings Faster (single-thread) Slower (multi-thread)
Usage Fixed content, map keys Building strings (single-thread) Building strings (multi-thread)

For most modern Java applications, if thread-safety is not a concern, StringBuilder is the recommended choice for mutable string operations due to its performance benefits. However, when working with legacy code or in specific multi-threaded scenarios, StringBuffer remains relevant. In both cases, the conversion to String is performed using the toString() method.

Conclusion

Converting a StringBuffer to a String in Java is a straightforward process achieved by invoking the toString() method on the StringBuffer object. This creates a new, immutable String object reflecting the StringBuffer's content at that moment, ensuring that subsequent changes to the StringBuffer do not affect the obtained String.