Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

StringBuilder.toString — obtaining text as a String

StringBuilder.toString() returns a String containing the builder's current contents. Later builder changes do not change the returned text.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

public String toString()
String result = builder.toString();

StringBuilder.toString() is a no-argument instance method returning a String containing the current character sequence. Call it on an object, for example builder.toString(), not on the class.

The method neither clears nor modifies the builder. The Java SE 21 documentation specifies allocation of a new String object; subsequent StringBuilder changes do not affect its contents.

In the example, snapshot retains Java 21 after ! is appended to the builder. The next builder.toString() returns Java 21!. Calling the method alone does not print text — System.out.println does that.

Examples

public class Main {
    public static void main(String[] args) {
        StringBuilder builder = new StringBuilder("Java");
        builder.append(" 21");
        String snapshot = builder.toString();
        builder.append("!");

        System.out.println(snapshot);
        System.out.println(builder.toString());
    }
}

Result

Java 21
Java 21!

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources