Java中的布尔表达式
我对 Java 中 return 语句中布尔变量的含义(评估)有疑问.
I have a question about the meaning (evaluation) of Boolean variables in return statements in Java.
我知道:
if (var) { ... }
等同于:
if (var==true) { ... }
在第二种情况下,我们明确地说 var==true,但我们不需要这样做,因为 Java 无论如何都会将 var 评估为 true.我希望我已经正确理解了这一点.
In the second case we explicitly say var==true, but we don't need to do this, because Java evaluates var as true anyway. I hope I have understood this right.
我的问题是:返回布尔变量时是否相同?什么时候有return语句?
My question is: is it the same when Boolean variables are returned? When we have a return statement?
例如,一个任务指定:方法looksBetter() 将仅在b <<;时返回true.一个.我的解决方案是:
For example, a task specifies: the method looksBetter() will return true only if b < a. My solution was:
public boolean looksBetter() {
if (b < a) {
return true;
} else {
return false;
}
}
简单的答案是:
public boolean lookBetter() {
return b < a;
}
所以,这里我们似乎再次有这个隐含的假设,即如果 b <;a == true,方法的返回为true.对不起......这似乎很微不足道,但我对此感到不舒服,我不知道为什么.谢谢.
So, it seems that here we have again this implicit assumption that in case b < a == true, the return of the method is true. I am sorry ... it seems very trivial, but I am somehow not comfortable with this, and I don't know why. Thank you.
推荐答案
这不是隐含假设",而是编译器在做的事情.b <a
只是一个表达式,就像它用于 if
语句一样.该表达式的计算结果为 boolean
,然后返回.
It's not an "implicit assumption," it's what the compiler's doing. The b < a
is just an expression, the same as if it were used for an if
statement. The expression evaluates to a boolean
, which is then returned.
同样值得注意的是,您似乎将 boolean
和 Boolean
互换,好像它们是相同的,但实际上并非如此.boolean
是 原始形式而 Boolean
是 一个对象 包装了一个 boolean
.
Also noteworthy, you seem to interchange boolean
and Boolean
as though they're the same, but they're actually not. boolean
is the primitive form while Boolean
is an Object that wraps a boolean
.
相关文章