当我们使用赋值而不是比较时,如何评估if/while条件? [英] How is if/while condition evaluated when we use assignments instead of comparison?
问题描述
在学习Java的OCA/OCP时,我发现了这一令人惊讶的事情.
I discovered this surprising thing while learning OCA/OCP for Java.
下面是if(测试条件)部分的第一段代码 令我惊讶.
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".
我了解到必须有一个关系条件,该条件必须像if (a > b)
或if (a != b)
一样返回true或false.
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. But
x = y
不仅将y
的 值分配给x
,还 返回 该值.因此,我们可以执行x=(y=1)
之类的操作(甚至可以在此处删除括号),该操作会将1
分配给y
,然后返回将1
分配给x
.
not only assign value of y
to x
, it also returns that value. Thanks to that we can do things like x=(y=1)
(we can even drop parenthesis here) which will assign 1
to y
, then return that 1
will be assigned to x
.
在您的情况下,首先在if (b = true)
中将true
分配给b
,然后将其返回,因此您以if(true)
结尾,因此它将始终从该布尔值的分支执行代码.
In your case in if (b = true)
first true
will be assigned to b
then it will be returned, so you end up with if(true)
so it will always execute code from branch for that boolean value.
这通常是印刷错误的结果,因为在大多数情况下,我们希望使用==
(等号运算符),而不是=
(赋值运算符).
This is often result of typographic error since in most cases we want ==
(equality operator), instead of =
(assignment operator).
为避免此错误,我们可以编写类似
To avoid this mistake we can write code like
-
作为
- -由于
b == true
始终为b
,因此我们跳过== true
部分.if
可以使用b
的值来代替对b == true
的求值.当我们想使用否定代替==false
时,我们可以编写if(!b){..}
- 使用尤达条件
if(true == b){..}
-如果由于错误而使用了=
的==
会得到编译错误,它会通知我们,因为我们不能像true
那样将 assign 分配给 value ,我们只能将值赋给变量.
if (b){..}
的- as
if (b){..}
- sinceb == true
is alwaysb
we skip== true
part.if
can use value ofb
instead of evaluatingb == true
. When we want to use negation instead of==false
we can writeif(!b){..}
- using Yoda conditions
if(true == b){..}
- if by mistake we will use=
instead of==
we will get compilation error which will inform us about it, because we can't assign anything to value liketrue
, we can only assign values to variables.
这篇关于当我们使用赋值而不是比较时,如何评估if/while条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!