首先,今天在一个群里有人向我问了这个问题。我不知道……
于是,本着“空谈误国,实干兴邦” 的精神,我决定看一下源码一探究竟
源码:
println:
/** * Prints an Object and then terminate the line. This method calls * at first String.valueOf(x) to get the printed object's string value, * then behaves as * though it invokes <code>{@link #print(String)}</code> and then * <code>{@link #println()}</code>. * * @param x The <code>Object</code> to be printed. */ public void println(Object x) { String s = String.valueOf(x); synchronized (this) { print(s); newLine(); } }
可以看到,println 里面首先会通过调用 String.valueOf(Object x); 来将对象转化成一个字符串。
然后调用 print 来打印,最后换行的。
String.valueOf();
- 那么我们在看一下 String.valueOf();
/** * Returns the string representation of the <code>Object</code> argument. * * @param obj an <code>Object</code>. * @return if the argument is <code>null</code>, then a string equal to * <code>"null"</code>; otherwise, the value of * <code>obj.toString()</code> is returned. * @see java.lang.Object#toString() */ public static String valueOf(Object obj) { return (obj == null) ? "null" : obj.toString(); }
- 现在很清楚了,在 String.valueOf();里面是先判空,不为空的情况下调用 toString();的。。。。
菜鸟一个,基础一点点积累。不喜勿喷。
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于