java中打印null
执行以下行时:
System.out.println(null);
结果在控制台上打印为 null 。
为什么会发生这种情况?
On execution of following line :
System.out.println(null);
the result comes out to be null printed on console.
Why does that happen?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
从 OpenJDK 1.6.0_22 的来源来看:
PrintStream:
String:
Telling from the sources of OpenJDK 1.6.0_22:
PrintStream:
String:
实际上,至少在java版本1.8.0中,
System.out.println(null);
不应该打印null
。您会收到一条错误消息,内容如下:对 println 的引用不明确,PrintStream 中的方法 println(char[]) 和 PrintStream 中的方法 println(String) 均匹配。
您必须按如下方式进行转换:
System.out.println((String)null) ;
请参阅 coderanch 帖子此处。我想你也可以做
System.out.println(null+"");
来完成同样的任务。Actually, at least in java version 1.8.0,
System.out.println(null);
should not printnull
. You would get an error saying something like:reference to println is ambiguous, both method println(char[]) in PrintStream and method println(String) in PrintStream match.
You would have to cast as follows:
System.out.println((String)null);
See coderanch post here.I suppose you could also do
System.out.println(null+"");
to accomplish same.因为这正是 Javadocs 所说的将会发生的情况?
http:// download.oracle.com/javase/6/docs/api/java/io/PrintStream.html#print(java.lang.String)
Because that's exactly what the Javadocs say will happen?
http://download.oracle.com/javase/6/docs/api/java/io/PrintStream.html#print(java.lang.String)
它最终调用 String.valueOf(Object) ,如下所示:
It's eventually calling
String.valueOf(Object)
which looks like:当我查看 PrintStream 我观察到(我在这里引用)
希望这能回答您的问题。
When I look at the javadoc for PrintStream I observe (I am quoting here)
Hopefully that should answer your question..