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中的布尔表达式
				
        
 
            
        - Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
 - value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
 - Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
 - Java包名称中单词分隔符的约定是什么? 2022-01-01
 - 如何使用WebFilter实现授权头检查 2022-01-01
 - 将log4j 1.2配置转换为log4j 2配置 2022-01-01
 - C++ 和 Java 进程之间的共享内存 2022-01-01
 - Eclipse 插件更新错误日志在哪里? 2022-01-01
 - 从 finally 块返回时 Java 的奇怪行为 2022-01-01
 - Jersey REST 客户端:发布多部分数据 2022-01-01
 
						
						
						
						
						