• Post Reply Bookmark Topic Watch Topic
  • New Topic

Java operations precedence

 
Laimonas Oberauskis
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I have got an equation:

x = 4;
long y = x * 4 - x++;

Why is y 12? Not 15?
According the precedence rules, x++ should be executed first. Then we should have y = 5 * 4 - 5 = 15. I know the correct answer is 12, but please help me understand this.
 
Jeanne Boyarsky
author & internet detective
Sheriff
Posts: 36032
432
Eclipse IDE Java VI Editor
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Laimonas,
Welcome to CodeRanch! It's an interesting question.

For this to make sense, imagine Java is adding parenthesis to specify the order. Your example is equivalent to:



Then it starts evaluating with the "inner" parens and we have:



Since x++ is postfix, this happens after the "4" is grabbed for the expression
 
Henry Wong
author
Sheriff
Posts: 22644
111
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also, this is the point where you misunderstood...

Laimonas Oberauskis wrote:
According the precedence rules, x++ should be executed first.


Precedence rules and Evaluation Order rules are not the same thing. Evaluation order, according to the JLS, is always left to right.

Henry
 
Laimonas Oberauskis
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much, guys!
 
Campbell Ritchie
Marshal
Posts: 53225
124
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch
Remember that in an expression like i++ there are two values. The value of i is one more than the old value of i, but that is hidden from you. The value of the whole expression, which is what you see, i.e. the value of i++, is equal to the old value of i.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!