-2
int a = 2;
int b = 3;
int c = 10;

  a +=(a += b) + c; // this will be same as --> a = a+((a= a+b) +c);    
  /*                                                  2+((2=2+3)+10)
                                                   after adding 2+3
                                                   now value a = 5;
                                                    5 +((5)+10)
                                                    5 + (15)
                                                a = 20
 */
System.out.println("a: "+a); // a:17 

when i execute above program the answer is a:17 why not a:20 ? according to me. After resolving (a += b) now the value of a should be 5 then (a += b) + c would be 15 and after that a +=(a += b) + c; should be 20 please help me understand thanks.

Mohsin AR
  • 2,998
  • 2
  • 24
  • 36

5 Answers5

1

This is a good example of where order of evaluation and precedence don't match. They usually do which makes it confusing when there is a difference, as you mention the expression is evaluated left to right like this

int s = a; // stack
int t = a + b; // second stack value.
s += t;
s += c;
a = t;
a = s;

Note the (a+=b) is the same as (a+b) in this case.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1

It is a bit tricky to understand. Although you have a += b on the right-hand side, that doesn't change the value of a that's used for the += at the beginning of the expression; that will still be 2. E.g.:

a += (a += b) + c;
a = 2 + (a[still 2] += 3) + 10
a = 2 + (5) + 10
a = 17

The a += b on the right-hand side is really just a a + b, since this is all on the right-hand side of a += already directed at a.

Details in JLS§15.26.2: Compound Assignment Operators.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

The compound assignment operator stores the original value of the left operand before evaluating the second operand and performing the compound assignment (addition + assignment in this example).

Therefore

a += (a += b) + c;

is equivalent to :

int temp = a;
a = temp + (a += b) + c;
     2   +   2 + 3  + 10 = 17
Eran
  • 387,369
  • 54
  • 702
  • 768
1

In Java, you can replace a += b with a = a + b. And that is very important.

Hence your expression is equivalent to

a = a + (a = a + b) + c

Note that this will be evaluated as a = Term1 + Term2 + Term3 and in the order left to right.

Term1 is 2.

Term2 is the only tricky one. It is 5 (and has the side-effect of increasing a to 5 but that gets clobbered by the eventual assignment).

Term3 is 10.

That recovers the total, 17.

Note that the behaviour of this expression in C and C++ is undefined.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0

First you do a+=b so 2+3 you have 5. Then a+= your answer (here 5) so 2+=5 = 7. Then 7+10 = 17

Sylvain Attoumani
  • 1,213
  • 1
  • 15
  • 34