如果在圆括号内的赋值情况下条件评估为真或假,该怎么办? [英] How does if condition evaluate true or false in case of assignments inside round brackets
问题描述
我在学习OCA / OCP for Java时发现了这个令人惊讶的事情。
I discovered this surprising thing while learning OCA/OCP for Java.
下面是if(测试条件)部分$ b $的第一段代码b让我感到惊讶。
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");
}
现在这个输出令人惊讶的是真实。
Now the output of this surprisingly is "true".
我了解到必须有一个关系条件,如果(a> b)或<$ c,则返回true或false,如 $ c> 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. 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)
first 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
- 这样的代码
if(b){..}
- 因为b == true
总是b
我们跳过== true
part。如果
可以使用b
的值而不是评估b == true
。当我们想要使用否定而不是== false
时,我们可以写if(!b){..}
- 使用 Yoda条件
if (true == b){..}
- 如果我们错误地使用=
而不是==
我们将收到编译错误,告知我们,因为我们无法将值分配给值,如true
,我们只能为变量分配值。
- 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.
这篇关于如果在圆括号内的赋值情况下条件评估为真或假,该怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!