Can someone explain why the answer is B? I am using Java and I do not understand
- Case (I) expands to x = x - (x + 4) according to the Java operator
-=
,
and mathematically simplifies to x = -4. - Case (II) is mathematically simplified to x = 4.
- Case (III) is mathematically simplified to x = -4.
Therefore (I) and (III) are the same, which means that the answer is (B).
source to share
-=
is a so-called compound destination.
They are just short cuts and merging of atomic operations.
x -= y
means x = x-y
x += y
means x = x+y
x++
means x = x+1
x--
means x = x-1
There are also ++ x and -x, which do the same as x ++ / x--, except that they return the value of x before it is incremented / decremented.
Official Java Tutorial:
"You can also combine arithmetic operators with a simple assignment operator to create complex assignments. For example, x + = 1; and x = x + 1; both increase x by 1."
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op1.html
I think the same works for *=
, /=
and%=
source to share