Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

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 v2

toString() 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
true

Notes

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

In the tutorial

  • StringBuilder — StringBuilder in Java: a mutable string, append, insert, reverse, deleteCharAt, call chains and building a string in a loop.

Thanks for reading!

Donate to the site — we work hard for you.