Win a copy of Bad Programming Practices 101 (e-book) this week in the Beginning Java forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Java operations precedence  RSS feed

 
Greenhorn
Posts: 11
  • 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.
 
author & internet detective
Marshal
Posts: 38367
645
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
 
author
Sheriff
Posts: 23553
138
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: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much, guys!
 
Marshal
Posts: 59409
187
  • 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.
 
A teeny tiny vulgar attempt to get you to buy our stuff
Why should you try IntelliJ IDEA ?
https://coderanch.com/wiki/696337/IntelliJ-IDEA
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!