[Logo]
Forums Register Login
Java unary operator evaluation order
1.class TQ{
2.public static void main(String args[]){
3.int var1=0x14;
4.var1 *=(--var1);
5.System.out.println(var1);
6.}
7.}

please explain the evaluation of expression on line 4.
(1 like)
 
Kajal Dusseja wrote:
please explain the evaluation of expression on line 4.


As specified by the JLS...

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

The evaluation of an expression is done from left to right.  I am assuming that you are confused because the pre-decrement operator is not done before the compound assignment operator?

Henry
(2 likes)
we have,var1=var1*(--var1)
→var1=var1*(--var1)
The R.H.S is an expression and you need to evaluate it.
expressions are always evaluated from left to right.so on rhs var1 will be replaced by its current value which is 0x14.now it will head towards the next operand of "*" which is (--var1) it is an another expression itself which is equivalent to "var1-1=var1".which will have value (0x14-0x1) and it will set this value for var1.now your expression evaluates to value (0x14)*(0x14-0x1) and then it will be assigned to var1.

Note:the value of var1 changes 2 times in this evaluation,1st one when you evaluate --var1 and finally when the expression after evaluation is aasigned to var1.

HIH

Kind Regards,
Praveen.
And Welcome to CodeRanch!
 
Henry Wong wrote:
Kajal Dusseja wrote:
please explain the evaluation of expression on line 4.


As specified by the JLS...

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

The evaluation of an expression is done from left to right.  I am assuming that you are confused because the pre-decrement operator is not done before the compound assignment operator?

Henry


Yes, I was bit confused over there, but that helped.
Thank You.
 
praveen kumaar wrote:we have,var1=var1*(--var1)
→var1=var1*(--var1)
The R.H.S is an expression and you need to evaluate it.
expressions are always evaluated from left to right.so on rhs var1 will be replaced by its current value which is 0x14.now it will head towards the next operand of "*" which is (--var1) it is an another expression itself which is equivalent to "var1-1=var1".which will have value (0x14-0x1) and it will set this value for var1.now your expression evaluates to value (0x14)*(0x14-0x1) and then it will be assigned to var1.

Note:the value of var1 changes 2 times in this evaluation,1st one when you evaluate --var1 and finally when the expression after evaluation is aasigned to var1.

HIH

Kind Regards,
Praveen.


Yes, got it.
Thank YoU .
Wink, wink, nudge, nudge, say no more ... https://richsoil.com/cards



All times above are in ranch (not your local) time.
The current ranch time is
Oct 23, 2017 09:51:59.