Java Unexped Outputs From Pre-Increment

41 views Asked by At

I am trying to figure out why the following code gives two different results

I tried the followingL

int x = 4, y = 4;
System.out.println(x + --x);
System.out.println(--y + y);

And It outputs 7 6. From my knowledge, preincrement has a higher precendence than addition so it should decrease the value of x/y regardless of it's value in the expression but this is clearly not the case. Can anyone please explain this to me?

1

There are 1 answers

0
Stultuske On
System.out.println(x + --x); 
System.out.println(--y + y);

This can be re-written as:

x + --x => x + (x = x-1) => 4 + 3 = 7

--y + y => (y = y-1) + y (y here is already decreased in value) = 3 + 3 = 6