当我们使用赋值而不是比较时,如何评估 if/while 条件? [英] How is if/while condition evaluated when we use assignments instead of comparison?
问题描述
我在学习 OCA/OCP for Java 时发现了这个令人惊讶的事情.
I discovered this surprising thing while learning OCA/OCP for Java.
下面是 if(test condition) 部分的第一段代码令我惊讶.
Below is the first piece of code of which the if(test condition) part surprises me.
public class BooleanIf {
public static void main(String[] args) {
boolean b = false;
System.out.println(Boolean.valueOf(b = true));
if (b = true)
System.out.println("true");
else
System.out.println("false");
}
现在这个令人惊讶的输出是true".
Now the output of this surprisingly is "true".
我了解到必须有一个返回 true 或 false 的关系条件,如 if (a > b)
或 if (a != b)
类似.
I learnt that there has to be a relational condition that returns true or false like if (a > b)
or if (a != b)
likewise.
我想知道在这种情况下它是如何返回 true 的.它会调用 Boolean.valueOf() 吗?
I want to know how it is returning true for this case. Does it call Boolean.valueOf()?
推荐答案
=
是赋值运算符,==
是比较运算符.
=
is assignment operator, ==
is comparison operator.
但是
x = y
不仅将值从y
赋值给变量x
,它还返回 那个值.
not only assigns value from y
to variable x
, but it also returns that value.
多亏了这一点,我们可以做诸如 x=(y=1)
(我们甚至可以在这里去掉括号)之类的事情,它将 1
分配给变量 y
,然后将返回该 1
并将其分配给 x
.
Thanks to that we can do things like x=(y=1)
(we can even drop parenthesis here) which will assign 1
to variable y
, then will return that 1
and also assign it to x
.
因此也可以编写像 if (b = true)
这样的代码,其中 true
将被分配给 b
然后由 if(..)
返回和使用.换句话说,你最终会得到类似 if(true){b=true; 的东西...}
所以它总是从 true
分支执行代码.
Because of that it is also possible to write code like if (b = true)
where true
will be assigned to b
and then be returned and used by if(..)
. In other words you end up with something like if(true){b=true; ..}
so it will always execute code from true
branch.
省略
==true
和==false
部分.
- 在
if(b==true)
的情况下,我们可以写if(b)
因为(b == true)
总是给出与b
中存储的 aleady 相同的结果. - 在
if(b==false)
的情况下,我们可以写if(!b)
.
- In case of
if(b==true)
we can writeif(b)
since(b == true)
will always give same result as aleady stored inb
. - In case of
if(b==false)
we can writeif(!b)
.
在==
左侧使用值代替变量.
换句话说,使用 Yoda conditions if(true == b){..}代码>.即使我们错误地写了
=
而不是 ==
我们最终会得到 true=b
这将导致编译错误,因为我们不能像 true
那样分配任何东西给 value.我们只能给变量赋值.
use value instead of variable on left side of ==
.
In other words use Yoda conditions if(true == b){..}
. Even if by mistake we will write =
instead of ==
we will end up with true=b
which will end up as compilation error since we can't assign anything to value like true
. We can only assign values to variables.
这篇关于当我们使用赋值而不是比较时,如何评估 if/while 条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!