Organization of hierarchy of operators "+ =" and "++"?

I got a little confused in the following short code snippet, why is the result not 4, but 3?

int i = 1;
i += ++i;
System.out.println(i);

I thought:

  • Calculate the right side ++i, iis 2;
  • Calculate +=, i = i + 2at this point in time, I thought it ishould now be 4, but the result is 3.
+4
source share
2 answers

Calculate the right side, ++ i

No, this is not the first step.

The first step is to evaluate the initial value of the left side. Then evaluate the right side. Sum them up and assign the result to a variable.

So,

i += ++i;

generally equivalent

i = i + (++i);

In particular, from JLS 15.26.2 , my attention:

  • , . , .

  • , . , .

+10

:

i += ++i;

=> i = i + ++i;  
=> i = 1 + ++i;
=> i = 1 + 2;

Java , , -, , .

+5

Source: https://habr.com/ru/post/1685369/


All Articles