Search code examples
javaoperator-precedence

How are y=x++ and y=x-- different when the assignment operators has the least priority?


I'm new to java. Just found out that in the expression, y=x++, y assumes the value of x and x becomes +1. Forgive me if I sound stupid, but according to the order of precedence, assignment operators is at the end. So isn't x++ supposed to happen first followed by the assignment. Thanks in advance.


Solution

  • Q: So isn't x++ supposed to happen first followed by the assignment.

    A: Yes. And that is what happens. The statement y = x++; is equivalent to the following:

    temp = x;      // | This is 'x++'
    x = x + 1;     // | (note that 'temp' contains the value of 'x++')
    
    y = temp;      // This is the assignment.
    

    But as you see, the order of the operations (++ and =) doesn't affect what the operations actually do.

    And therefore ...

    Q: How are y=x++ and y=x-- different when the assignment operators has the least priority?

    A: They aren't.