Win a copy of Bad Programming Practices 101 (e-book) this week in the Beginning Java forum!
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:
Sheriffs:
Saloon Keepers:
Bartenders:

# 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
Marshal
Posts: 38367
645
• 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
Sheriff
Posts: 23553
138
• 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: 59409
187
• 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.

 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