StringBuilder应该在打印之前转换为String吗?

Cel*_*tas 2 java stringbuilder

如果直接完成打印StringBuilder对象的内容或者.toString()调用该方法,它会有所不同吗?

特别是

StringBuilder sb = new StringBuilder("abc");
System.out.println(sb);
System.out.println(sb.toString());
Run Code Online (Sandbox Code Playgroud)

一种风格比另一种更受欢迎吗?

任何人都可以评论为什么第一种方式有效?在Java中是否System.out.println隐式调用.toString()了对象的方法?

awk*_*ksp 5

正如您猜测的那样,PrintStream#println(Object)确实会自动调用toString()对象的方法:

public void println(Object x) {
    String s = String.valueOf(x);
    synchronized (this) {
        print(s);
        newLine();
    }
}
Run Code Online (Sandbox Code Playgroud)

在哪里String.valueOf():

public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}
Run Code Online (Sandbox Code Playgroud)