1

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

3
  • i2 is set to 2 midway through the expression. First it's 3, then it's 2. Commented Aug 31, 2020 at 23:07
  • Left-to-right evaluation is still the rule, and assignment happens whenever it's encountered in that order. Commented Aug 31, 2020 at 23:09
  • @LouisWasserman thank you a lot! Now it's clear int i3 = (i2 = i1) + i2 will give 4. Bytecode gave more understanding Commented Aug 31, 2020 at 23:20

1 Answer 1

3

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:

  1. Take value of i2, call it 'tmp1'
  2. Take address of i2, call it 'tmp2'
  3. Take value of i1
  4. Store a copy of that value at address 'tmp2'
  5. Add the value in hand to the value of 'tmp1'
  6. which is the result of the expression

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.

Sign up to request clarification or add additional context in comments.

3 Comments

You ought to be able to infer it: in 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.
Much better. We should always be careful with the word “always”.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.