[英]System.out.println Not doing what I expect when printing something that evaluates to a boolean
I'm not sure how to describe my question for a title, so here's my code: 我不确定如何描述标题问题,所以这是我的代码:
public class NullLogic {
public static void main(String[] args) {
NullLogic nl = new NullLogic();
System.out.println("nl.getNull() = " + nl.getNull() );
System.out.println("nl.getNull() == null = " + (nl.getNull() == null) );
System.out.println("nl.getNull() == null = " + nl.getNull() == null );
}
private String getNull() {
return null;
}
}
Here's the output: 这是输出:
nl.getNull() = null
nl.getNull() == null = true
false
Ok---the first line is no problem, exactly what I'd expect. 好的-第一行没问题,正是我所期望的。 Second line is also good.
第二行也不错。
Now I've got a problem with the third line, I know the statement that evaluates to a boolean should be in brackets, but I figure I should get a runtime error or something, not a successful execution that suppresses the the string part of the sysout. 现在我在第三行遇到问题,我知道应该将计算为布尔值的语句放在方括号中,但是我认为我应该遇到运行时错误或某些错误,而不是成功执行会抑制字符串的字符串部分sysout。
What's going on here? 这里发生了什么?
This isn't a serious problem that I need to solve, but I don't know what's going on here and I'd like to know. 这不是我需要解决的严重问题,但我不知道这里发生了什么,我想知道。
Thanks! 谢谢!
System.out.println("nl.getNull() == null = " + nl.getNull() == null )
is evaluated as 被评估为
System.out.println(("nl.getNull() == null = " + nl.getNull()) == null )
ie, first you concatenate two String
s (the first is not null - "nl.getNull() == null = "
, and the second is null
, but even if both were null
, concatenating them would result in a not null
String
). 即,首先连接两个
String
(第一个不为"nl.getNull() == null = "
,第二个为null
,但是即使两个均为null
,将它们串联也将导致一个非null
String
) 。
The result of this concatenation is the String
: "nl.getNull() == null = null"
. 串联的结果是
String
: "nl.getNull() == null = null"
。
Then you compare "nl.getNull() == null = null"
to null
, which evaluates to false
. 然后,将
"nl.getNull() == null = null"
与null
,其结果为false
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.