Page 1 of 1

About Question enthuware.ocajp.i.v8.2.1402 :

Posted: Fri Apr 03, 2015 9:24 am
by alkour
Hi,

Could I ask to explain logic behind the statement:

int x2 = x1--;

First it will be the assignment (=) than decrement of x1 - (--) postfix operation.

But how this logic comply with the rule that postfix operation has higher precedence than assignment (=) operation.

Re: About Question enthuware.ocajp.i.v8.2.1402 :

Posted: Fri Apr 03, 2015 9:43 am
by admin
There are two things that you need to know - value of the expression and value of the variable.
An expression can be composed on multiple variables. The value of the expression is the value of the whole of the right hand side of = operator. While the value of a variable is just the value of a variable. For example, if you have a = 1 and b=1,

a = b+1; //here b+1 is an expression and b is a variable. The value of the expression is 2, and the value of the variable b is 1
a = b; //here b is an expression and b is a variable as well. The value of the expression is 1, and the value of the variable b is also 1

In expressions involving Post increment/decrement the value of the expression and value of the variable are not same. In case of int x2 = x1--; the expression is x-- and its value is the value of x before x is decremented. The value of the variable x is x-1. This is how postfix operators are defined in JLS 15.14.2.

So to answer your question, the rule is still valid if you look at the value of the expression, which is computed first and then assigned to the left hand side variable.

HTH,
Paul.

Re: About Question enthuware.ocajp.i.v8.2.1402 :

Posted: Fri Apr 03, 2015 10:20 am
by alkour
Thank you. Now much more clear.

Re: About Question enthuware.ocajp.i.v8.2.1402 :

Posted: Sat Sep 05, 2020 5:00 am
by egorko
x3 is ++(x2) => x2 becomes -3 first and then its value i.e. -3 is assigned to x3 is a tricky part.
I assigned all correctly before but ignored ++x2 changes x2 as well