0

I'm a bit confused about this code:

int r = 7;
boolean result1 = r == r++; //
boolean result2 = r++ == r; //

System.out.println(result1);
System.out.println(result2);

I would think both are true, but result1 is true and result2 is false.

The Oracle tutorial doesn't really help, in the Java Language Specification I also don't find any answer. So far, I don't understand, how the post-increment operator has the highest operator precedence.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • Try saying out loud, for `result1` "Is 7 equal to 7, then incremented 7 by one?" and, for `result2` "is 8 incremented by 1 equal to 8?" And you can also experiment with parentheses around things to force precedence. – Mark Stewart Nov 25 '20 at 16:41
  • 3
    Does this answer your question? [How do the post increment (i++) and pre increment (++i) operators work in Java?](https://stackoverflow.com/questions/2371118/how-do-the-post-increment-i-and-pre-increment-i-operators-work-in-java) – Savior Nov 25 '20 at 16:49
  • Even in Java, it's possible to write very obscure code, and this is an example. More than operator precedence, hopefully this teaches a lesson about coding style - that we'll never ever write lines like these in production code. – Ralf Kleberhoff Nov 25 '20 at 17:50
  • 1
    This doesn't really have to do with operator precedence, but with order of evaluation, which is left to right. – Mark Rotteveel Nov 26 '20 at 17:23

1 Answers1

0

Java evaluate expressions one by one.

When it evaluate r++ result is 7, but side effect applied immediately, so when it evaluates r, result is new value of r (8).

This is the reason why increment/decrement expression should not be used in complex expressions.

talex
  • 17,973
  • 3
  • 29
  • 66