How does Java handle the expression x = x - (x = x - 1)?

I just tested the following code:

int x = 90;

x = x - (x = x - 1);
System.out.print(x);

He is typing 1.

As far as I understand, everything goes in the following order:

  • x - 1 computed and stored in a temporary variable in memory.
  • x the result from the temporary variable from element 1 is assigned.
  • Then it is calculated x - the new value of x.
  • The result is assigned x;

I do not understand why x, from which we subtract the result of paragraph 2, it still has an initial value after paragraph 2. What am I missing?

+4
source share
3 answers

From https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html

, , ; .

90 - (90 - 1) = > 1

. , .


@ruakh, JLS - .

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

, .

(ยง15.26.2), , , .

, , -, .

, , , , , , .

+6

:

int x = 90;
x = x - (x = x - 1);

= , .

x = x - (x = x - 1) x - b, b (x = x - 1)

, 90 - b

b, (x = x - 1). , (x = 90 - 1) (x = 89)

, 90 - (x = 89), 90 - 89, 1. , x 1. , (x = 89 ) .

+1
   int x = 90;
   x = x - (x = x - 1);
   System.out.print(x);`
Here
x = 90 Goes in two section in your code.
First x=90 - , Second  (x=90-1);
Then x=90  - , x = 89 
Then x= 90 - 89
       System.out.Print(x);
that is x=1;
+1
source

Source: https://habr.com/ru/post/1659950/


All Articles