Search code examples
javastringstringbuilder

Why do we need to use toString method with StringBuilder?


What is the difference between line 6 and line 8?

They both print the same string. Why do we need to use toString with StringBuilder?

StringBuilder s = new StringBuilder("hello");   // Line 1
System.out.println(s);                          // Line 2

s.append("hi");                                 // Line 3
System.out.println(s);                          // Line 4

s.append("okk");                                // Line 5
System.out.println(s);                          // Line 6

s.toString();                                   // Line 7
System.out.println(s);                          // Line 8

Solution

  • There's nothing different between line 6 and line 8.

    PrintStream.println(Object) calls string.valueOf(Object) which calls the object's toString() method, and that gets printed.

    System.out.println(s) and System.out.println(s.toString()) have the same output (unless s is null, in which case the latter throws an exception).

    The reason you call s.toString() directly is to get the current "built" value from the StringBuilder as a string so you can pass it on to other code which expects a string. If the code you want to call takes a StringBuilder you could just pass s, but then the called code has the ability to modify your value (they can't with string because it is an immutable data type).