-1

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?

shmosel
  • 49,289
  • 6
  • 73
  • 138
  • 2
    "Having precedence" doesn't mean "evaluated first". The first `x` is evaluated (let's call it `x1`, with value 4), than `--x` is evaluated (let's call it `x2`, with value 3), then `x1 + x2` is evaluated (so `4 - 3` so 7). – Federico klez Culloca Jan 18 '23 at 07:56

1 Answers1

2
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

Stultuske
  • 9,296
  • 1
  • 25
  • 37