StringBuilder.toString()
Returns the contents of a StringBuilder as a regular String.
Available since: Java 5
Syntax
public String toString()Return value
StringA new string with the current contents.
Examples
The result is an independent copy:
void main() {
var sb = new StringBuilder("draft");
String saved = sb.toString();
sb.append(" v2");
IO.println(saved);
IO.println(sb.toString());
}Output:
draft
draft v2toString() is needed to compare contents:
void main() {
var sb = new StringBuilder("abc");
IO.println(sb.equals("abc"));
IO.println(sb.toString().equals("abc"));
}Output:
false
trueNotes
IO.println(sb) and concatenation "x" + sb call toString() for you. Call it explicitly when you need an actual String: to return it, compare it or put it into a collection of strings.
See also
- StringBuilder — A mutable string: useful when text is built piece by piece, especially in a loop.
- StringBuilder.append() — Adds a value to the end of a StringBuilder.
In the tutorial
- StringBuilder — StringBuilder in Java: a mutable string, append, insert, reverse, deleteCharAt, call chains and building a string in a loop.