• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

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
Posts: 38921
686
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
Posts: 23811
140
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: 61777
193
  • 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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!