简体   繁体   中英

Can someone explain why the answer is B? I'm using Java and I don't understand

Which of the following statements are the same?

(I) x -= x + 4

(II) x = x + 4 - x

(III) x = x - (x + 4)

A. (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

is equivalent to

x = x - (x+4)

So assuming (II) x = x - (x + 4) was supposed to be (III) x = x - (x + 4) (since you have two options marked as (II) ), (I) and (III) are the same.

It's because of operator precedence. Java evaluates that as if it were

x -= (x+4)

so it first computes (x+4) and then subtracts that from x -- which is what the - part of -= means -- and then updates x , which is 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) mathematically simplifies to x = 4.
  • Case (III) mathematically simplifies to x = −4.

Therefore (I) and (III) are the same, which means the answer is (B).

-= is a so called compound assignment.

Those are just short-cuts and combine atomic operations.

x -= y stands for x = xy

x += y stands for x = x+y

x++ stands for x = x+1

x-- stands for x = x-1

There also are ++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 the arithmetic operators with the simple assignment operator to create compound assignments. For example, x+=1; and x=x+1; both increment the value of x by 1."

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op1.html

I think the same works for *= , /= and %=

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM