在Java中的布尔前pressions [英] Boolean expressions in Java

查看:81
本文介绍了在Java中的布尔前pressions的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个布尔变量在Java中return语句的含义(评价)的问题。

I have a question about the meaning (evaluation) of Boolean variables in return statements in Java.

我知道:

if (var) { ... }

是相同的:

if (var==true) { ... }

在第二种情况下,我们明确地说,VAR ==真实的,但我们并不需要这样做,因为Java评估var当成真正的反正。我希望我已经明白这个权利。

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()将返回true,只有当B<一个。我的解决办法是:

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&LT;一个== 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&LT;一个只是一个前pression,一样的,如果它被用于一个如果语句。这位前pression计算结果为布尔,然后返回。

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.

另外值得一提,你似乎交汇处布尔布尔好像它们是相同的,但他们其实不重。 布尔是的原始形式,而布尔是的一个封装了布尔对象

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中的布尔前pressions的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆