0

I just strugle to understand something about java operator precedence and assignments. Here the example:

int a = 10, b = 20;

int c = a + (a = b) * 0;

Why is the result c = 10? This means that for the first a in the calculation the old value of a is used. But the assigment in ( ) should have a higher precedence than the addition. Why isn't it done first?

Werzi2001
  • 2,035
  • 1
  • 18
  • 41
  • 3
    I don't know the answer, but please, never write code like this in a real-world project. – Bart Friederichs Feb 26 '18 at 11:28
  • 6
    The addition is evaluated left-to-right, I believe. By the time we evaluate `(a=b)` the left operand was already evaluated and locked in. –  Feb 26 '18 at 11:29
  • @BartFriederichs Of course. It's from an "tricky code questions" example. – Werzi2001 Feb 26 '18 at 11:32
  • @Arkadiy But doesn't the operator precedence change excactly that? So the order in which operands are evaluated. – Werzi2001 Feb 26 '18 at 11:33
  • 2
    Operator precedence decides whether it's `(a+b)*0` or `a+(b*0)`. The order of execution is not affected. –  Feb 26 '18 at 11:37

0 Answers0