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

Viewed 192

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.

3 Answers

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.

Operator precedence and evaluation order are two different concepts and they're not related.

If you have a() + b() * c(), that doesn't mean that b() and c() get invoked first because * has a higher precedence than +. a() still gets evaluated first. Evaluation order is typically left-to-right unless stated otherwise.

The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.

https://docs.oracle.com/javase/specs/jls/se14/html/jls-15.html#jls-15.7

y=x++ is assigning the value of x to y and then x gets incremented. The x++ operation is called a post-increment.

Here's some code that you can run for illustration:

int x = 0;
System.out.println("Illustration of post-increment");
System.out.println(x);
System.out.println(x++);
System.out.println(x);

int y = 0;
System.out.println("Illustration of pre-increment");
System.out.println(y);
System.out.println(++y);
System.out.println(y);

Related