This question already has an answer here:
这个问题已经有了答案:
- What's this =! operator? [duplicate] 13 answers
- 这是什么= !运营商吗?(重复)13的答案
I was looking over some mock OCJP questions. I came across a really baffling syntax. Here it is:
我在看一些模拟OCJP问题。我遇到了一个令人困惑的语法。这里是:
class OddStuff {
public static void main(String[] args) {
boolean b = false;
System.out.println((b != b));// False
System.out.println((b =! b));// True
}
}
Why does the output change between !=
and =!
?
为什么输出会在!=和=之间变化?
4 个解决方案
#1
110
The question is just playing with you with confusing spacing.
问题是和你玩的时候,空格是混淆的。
b != b
is the usual !=
(not equals) comparison.
b != b是通常的比较。
On the other hand:
另一方面:
b =! b
is better written as b = !b
which is parsed as:
b = !b最好写成b = !b,解析为:
b = (!b)
Thus it's two operators.
因此,两个操作符。
- First invert
b
. - 第一个转化b。
- Then assign it back to
b
. - 然后把它分配给b。
The assignment operator returns the assigned value. Therefore, (b =! b)
evaluates to true - which is what you print out.
赋值操作符返回赋值。因此,(b = !b)计算结果为真——这是你打印出来的。
#2
10
b != b
means ! (b == b)
: the opposite of b == b
.
b != b的意思!(b = b): b = b的反义词。
b =! b
is actually b = !b
, an assignment. It's toggling b
's value. An assignment evaluates to the value of the expression, so this will evaluate to !b
(along with having changed the value of b
).
b = !b实际上是b = !这是切换b的值。赋值计算表达式的值,因此它将计算为!b(同时更改了b的值)。
#3
9
b=!b
is an assignment. It assigns b
to !b
and the expression evaluates to the resulting value, which is true
.
b = !b是一个任务。它将b赋给!b,表达式计算得到结果值,这是正确的。
#4
3
b =! b
b = !b
you are doing an assignment, you are saying that B should have the value of !B.
你在做作业,你是说B应该有B的值。
b != b
b ! = b
You are asking if B is different than b
你问的是B和B是否不同
#1
110
The question is just playing with you with confusing spacing.
问题是和你玩的时候,空格是混淆的。
b != b
is the usual !=
(not equals) comparison.
b != b是通常的比较。
On the other hand:
另一方面:
b =! b
is better written as b = !b
which is parsed as:
b = !b最好写成b = !b,解析为:
b = (!b)
Thus it's two operators.
因此,两个操作符。
- First invert
b
. - 第一个转化b。
- Then assign it back to
b
. - 然后把它分配给b。
The assignment operator returns the assigned value. Therefore, (b =! b)
evaluates to true - which is what you print out.
赋值操作符返回赋值。因此,(b = !b)计算结果为真——这是你打印出来的。
#2
10
b != b
means ! (b == b)
: the opposite of b == b
.
b != b的意思!(b = b): b = b的反义词。
b =! b
is actually b = !b
, an assignment. It's toggling b
's value. An assignment evaluates to the value of the expression, so this will evaluate to !b
(along with having changed the value of b
).
b = !b实际上是b = !这是切换b的值。赋值计算表达式的值,因此它将计算为!b(同时更改了b的值)。
#3
9
b=!b
is an assignment. It assigns b
to !b
and the expression evaluates to the resulting value, which is true
.
b = !b是一个任务。它将b赋给!b,表达式计算得到结果值,这是正确的。
#4
3
b =! b
b = !b
you are doing an assignment, you are saying that B should have the value of !B.
你在做作业,你是说B应该有B的值。
b != b
b ! = b
You are asking if B is different than b
你问的是B和B是否不同