Boolean expressions in Java(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
.
这篇关于Java中的布尔表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java中的布尔表达式
基础教程推荐
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 降序排序:Java Map 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01