# Java operations precedence

Laimonas Oberauskis

Greenhorn

Posts: 5

posted 1 month ago

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.

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.

posted 1 month ago

- 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

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

[OCA 8 book] [OCP 8 book] [Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]

Other Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, TOGAF part 1 and part 2

Campbell Ritchie

Sheriff

Posts: 52001

90