Converting Between String and StringBuilder
What you'll learn: How to seamlessly move data back and forth between immutable Strings and mutable StringBuilders.
The Core Idea
After building or modifying content in a StringBuilder, you'll eventually need an immutable String to use elsewhere in your program. Conversely, you often start with a String and need to convert it into a StringBuilder for efficient modifications. Java provides simple, dedicated mechanisms for both directions.
Think of it like working with clay: you mold the clay (StringBuilder) until you're satisfied, then you fire it in a kiln to create a permanent ceramic piece (String). Or, you can take an existing ceramic piece and create a fresh lump of clay from its design to make modifications.
From StringBuilder to String: toString()
Every StringBuilder has a toString() method that creates and returns a new immutable String containing the current character sequence:
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
String result = sb.toString(); // "Hello World"
The StringBuilder remains unchanged and independent after this conversion.
From String to StringBuilder: Constructors
To create a StringBuilder from an existing String, pass the string to the StringBuilder constructor:
String original = "Modify me";
StringBuilder sb = new StringBuilder(original);
sb.append("!");
// original remains "Modify me"
// sb now contains "Modify me!"
This copies the string's content into a new, mutable builder. The original string remains immutable and unaffected by subsequent modifications.
Practical Usage
This two-way conversion is fundamental: you typically start with strings, use StringBuilder for heavy modification work, then extract the final result with toString().
String input = "example";
StringBuilder builder = new StringBuilder(input);
builder.reverse();
String output = builder.toString(); // "elpmaxe"
Key Takeaway:
Use toString() to extract an immutable String from a StringBuilder, and use the StringBuilder constructor to create a mutable builder from an existing String—these conversions are cheap and essential for efficient string manipulation.