The toString() method of the StringBuilder class is the inbuilt method used to return a string representing the data contained by StringBuilder Object. A new String object is created and initialized to get the character sequence from this StringBuilder object and then String is returned by toString().
- It does not modify the original StringBuilder.
- The returned object is immutable because String is immutable.
public class Main {
public static void main(String[] args) {
// Creating StringBuilder object
StringBuilder str = new StringBuilder("GeeksForGeeks");
// Converting StringBuilder to String
String result = str.toString();
System.out.println("String: " + result);
}
}
Output
String: GeeksForGeeks
Explanation: The toString() method converts the contents of the StringBuilder into a String.
Syntax
public String toString()
Return Value: This method returns a String containing the characters currently stored in the StringBuilder.
Example: toString() After Modifying StringBuilder
public class Main {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder("Hello");
// Convert to String
String str = builder.toString();
// Modify StringBuilder
builder.append(" World");
System.out.println("StringBuilder: " + builder);
System.out.println("String: " + str);
}
}
Output
StringBuilder: Hello World String: Hello
Explanation: The String returned by toString() contains the contents of the StringBuilder at the time of conversion. Later changes to the StringBuilder do not affect the already-created String.
Example: Convert an Array of Strings into a Single String
public class Main {
public static void main(String[] args) {
String[] words = {"Are", "You", "A", "Programmer"};
StringBuilder builder = new StringBuilder();
for (String word : words) {
if (builder.length() > 0) {
builder.append(" ");
}
builder.append(word);
}
// Convert StringBuilder to String
String result = builder.toString();
System.out.println(
"Single String: " + result
);
}
}
Output
Single String: Are You A Programmer
Explanation: The array elements are appended to the StringBuilder with spaces between them. Finally, toString() converts the complete character sequence into a String.
Why Use toString() with StringBuilder?
- Converts to String: Converts the mutable StringBuilder content into an immutable
String. - Useful for returning results: Methods that require a
Stringcan use the result of toString(). - Works efficiently with StringBuilder: Multiple modifications can be performed before creating the final
String. - Preserves the current content: The returned
Stringrepresents the contents at the time toString() is called.
Advantages of StringBuilder toString() Method
- Converts StringBuilder content into a String.
- Provides an immutable String result.
- Preserves the content at the time of conversion.
- Useful when a String is required as the final result.
- Simple and easy to use.
- Allows multiple modifications before converting to String.