Search code examples
javaoperator-precedence

java beginner, operator precedence table


I look at the operator precedence table and ++ operator comes before = operator. But to compute this expression, b=a++; first, a is assigned to b and then a is incremented. This is confusing. Which one comes first, ++ or =?


Solution

  • Yes, ++ has higher precedence than =. But you need to think of the ++ post-increment operator as 2 operations -- increment the variable and yield the old value -- that happen before the operator with lower precedence, =.

    Here is what happens:

    1. Post-increment Operator ++: Increment a.
    2. Post-increment Operator ++: Yield the old value of a.
    3. Operator =: Assign the old value of a to b.

    It's equivalent to this code.

    int resultOfPostIncrement = a;
    a = a + 1;
    b = resultOfPostIncrement;