I have a code snippet example
int i1 = 2;
int i2 = 3;
int i3 = i2 + (i2 = i1);
Please can anyone explain to me why i3 will be initialized with 5 in this case? I thought that i2 after (i2 = i1) will be 2. And i2 + i2 will be 4
You are making the common error of confusing operator priority with order of evaluation of operands.
Priority affects the structure (i.e., meaning) of the expression only. Since you use explicit parentheses, there's no real doubt in i2 + (i2 = i1) -- it can't possibly mean (i2 + i2) = i1.
HOWEVER, in Java, evaluation of operands is always left-to-right. So `i2 + (i2 = i1)' means:
This sequence is didactic only, I do not mean this is the actual object code produced by the compiler. But it is how to understand what result you'll get.
In practice, though, you don't want to be writing code that's combining assignments to a variable and using the prior value of the variable. If I were doing the code review, I'd advise you to reformulate.
i2 + (i2 = i1) the operation of assignment to i2 has to happen before the addition of the prior value of i2 and the result of the assignment, Compare i2 + i3 * i4 - I assume it's self-evident that the multiplication has to occur before the addition, but nevertheless, that is "evaluation from left to right". The JLS is naturally a little stricter in its descriptions. However, I will now include the word 'operand' in my answer. Thanks.
i2is set to 2 midway through the expression. First it's 3, then it's 2.int i3 = (i2 = i1) + i2will give 4. Bytecode gave more understanding