operator precedence - How does Java process the expression x = x - (x = x - 1)? -
i tested following code:
int x = 90; x = x - (x = x - 1); system.out.print(x);
it prints 1.
as far understand, things go in following order:
x - 1
computed , stored temporary variable in memory.x
assigned result temporary variable item 1.- then
x - new value of x
calculated. - the result assigned
x
;
i don't understand why x
subtract result of item 2 still has initial value after item 2. missing?
from https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
all binary operators except assignment operators evaluated left right; assignment operators evaluated right left.
you doing 90 - (90 - 1)
=> 1
it's important not confuse precedence order of evaluation. related not same.
edit
as @ruakh points out, jls spec put differently tutorial above.
http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.7.
the left-hand operand of binary operator appears evaluated before part of right-hand operand evaluated.
if operator compound-assignment operator (§15.26.2), evaluation of left-hand operand includes both remembering variable left-hand operand denotes , fetching , saving variable's value use in implied binary operation.
if evaluation of left-hand operand of binary operator completes abruptly, no part of right-hand operand appears have been evaluated.
rather assignment evaluated right left, treats assignment first store of variable updated, evaluation of value , assignment.
Comments
Post a Comment