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

Greenhorn
Posts: 11
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
• 1
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
• 1
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
Thank you very much, guys!

Marshal
Posts: 61777
193
• 1
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.