Celeritas
Celeritas

Reputation: 15043

Should StringBuilder be converted to String before printing out?

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?

Upvotes: 2

Views: 86

Answers (1)

awksp
awksp

Reputation: 11867

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();
}

Upvotes: 5

Related Questions