2

Does it make a difference if printing the contents of a StringBuilder object is done directly or if the .toString() method is called?

In particular

StringBuilder sb = new StringBuilder("abc");
System.out.println(sb);
System.out.println(sb.toString());

Is one style preferred over the other?

Can anyone comment on why the first way works? In Java does System.out.println implicitly call the .toString() method of an object?

2

1 Answer 1

5

As you guessed, PrintStream#println(Object) indeed automatically calls the toString() method of an object:

public void println(Object x) {
    String s = String.valueOf(x);
    synchronized (this) {
        print(s);
        newLine();
    }
}

Where String.valueOf() is:

public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.