Can someone explain why the answer is B? I am using Java and I do not understand
Which of the following statements are the same?
(I) x - = x + 4
(II) x = x + 4 - x
(III) x = x - (x + 4)
and. (I) and (II) are the same
B. (I) and (III) are the same
C. (II) and (III) are the same
D. (I), (II) and (III) are the same
x -= y is equivalent to x = x - y
therefore
x -= x + 4
equivalent to
x = x - (x+4)
Suppose it (II) x = x - (x + 4)
should have been (III) x = x - (x + 4)
(since you have two options marked as (II)
) (I)
and are the (III)
same.
This is due to operator priority. Java evaluates that as if it were
x - = (x + 4)
so it first calculates (x+4)
and then subtracts from x
- what the -
part means -=
and then updates x
what the part =
means.
- 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).
-=
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%=