CodeBlanks Logo Icon CodeBlanks

toString

Learn to obtain a string with toString.

toString: getting the final text

When you are done, you turn the StringBuilder into a String with toString. This method does not change the builder's content; it returns a new String.

StringBuilder sb = new StringBuilder();
sb.append("Done");
String result = sb.toString();
// "Done"

Most of the time println automatically calls toString; so printing works even if you do not write it explicitly. But to store in a variable or pass to another method, toString is required.

Reusing the builder

After finishing, you can take toString and keep using the builder. Because toString does not clear the builder; it just returns a copy String.

StringBuilder sb = new StringBuilder("A");
String a = sb.toString();  // "A"
sb.append("B");
String ab = sb.toString();  // "AB"

If you want to start the builder over, you can write sb.setLength(0). This is cheaper than creating a new object; especially when you reset often in a loop.

Practice Turn step into text

Create a StringBuilder; append "Step ", "5" and " - done" with append. Store the result in a String variable using toString and print it with println.

Starter code

Main.java
public class Main {
  public static void main(String[] args) {
    // Create a StringBuilder
    // Append three parts
    // Store in a String variable with toString and print
  }
}

Sample solution

Main.java
StringBuilder sb = new StringBuilder();
sb.append("Step ");
sb.append("5");
sb.append(" - done");
String result = sb.toString();
System.out.println(result);

Expected output

Step 5 - done

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What happens if you print a StringBuilder with println?

  • toString is called automatically; the content is printed Correct answer
  • It throws an error
  • The address is printed
  • Only the first character

Explanation: println calls toString automatically.

2 Match scenario to approach

Term Meaning
Concat 2 texts once String +
100 appends in a loop StringBuilder
Turn builder into String toString
Flip the text reverse

3 Fill in the blank: convert to String

Question
StringBuilder sb = new StringBuilder("Done");
String result = sb.____();
Answer
StringBuilder sb = new StringBuilder("Done");
String result = sb.toString();

Explanation: sb.toString() returns a String.

All lessons in Beginner