Reputation: 15043
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
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