Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Organization of operator hierarchy of '+=' and '++'? [duplicate]

Tags:

java

operators

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

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

What I thought is:

  1. Calculate the right side, ++i, i is 2 then;
  2. Calculate the +=, i = i + 2, at this time point, I thought i should be 4 now, but the result is 3.
like image 221
mckf111 Avatar asked Dec 05 '22 13:12

mckf111


2 Answers

Calculate the right side, ++i

No, that's not the first step.

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

So

i += ++i;

is broadly equivalent to

i = i + (++i);

In particular, from JLS 15.26.2, emphasis mine:

  • Otherwise, the value of the left-hand operand is saved and then the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.

  • Otherwise, the saved value of the left-hand variable and the value of the right-hand operand are used to perform the binary operation indicated by the compound assignment operator. If this operation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.

like image 169
Jon Skeet Avatar answered Dec 28 '22 23:12

Jon Skeet


The Evaluation Order is as:

i += ++i;

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

The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.

like image 30
Naman Avatar answered Dec 28 '22 22:12

Naman