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:

  1. x - 1 computed , stored temporary variable in memory.
  2. x assigned result temporary variable item 1.
  3. then x - new value of x calculated.
  4. 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

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -