EdmDroid
EdmDroid

Reputation: 1360

Why is the operator precedence not followed here?

In this code:

int y = 10;
int z = (++y * (y++ + 5)); 

What I expected

First y++ + 5 will be executed because of the precedence of the innermost parentheses. So value of y will be 11 and the value of this expression will be 15. Then ++y * () will be executed. So 12 * 15 = 180. So z=180

What I got

z=176

This means that the VM is going from left to right not following operator precedence. So is my understanding of operator precedence wrong?

Upvotes: 22

Views: 3043

Answers (5)

haccks
haccks

Reputation: 106102

The parentheses just describe how the sub-expressions will be grouped together. Parenthesizing doesn't mean it will be evaluated first. Rather, the rule in java is evaluate each sub-expression strictly from left to right.

Always remember that the order of evaluation has absolutely nothing to do with operator precedence and associativity.

Java Oracle documentation says that:

15.7. Evaluation Order

The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.

Therefore, the expression (++y * (y++ + 5)) will be evaluated as

temp1 = ++y = 11
temp2 = y++ + 5 = 11 + 5 = 16 
z = temp1*temp2 = 11*16 = 176  

Further reading: Eric Lippert's blog, Precedence vs Associativity vs Order, explained in detailed about precedence, associativity and order of evaluation. Though this blog addresses but equally valid for too.

Upvotes: 13

Masudul
Masudul

Reputation: 21981

The calculation is going on following order

 z= (++10 * (10++ + 5))
 z= (11 * (11 + 5))//++ (prefix or postfix) has higher precedence than + or *
 z= (11 * 16)
 z= 176 

Upvotes: 1

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62874

  1. First will be executed ++y. y will be 11.
  2. Then will be executed y + 5 (actually y++ + 5 can be written as 5 + y++ which is interpreted as (5 + y) and then y++). z will become 11 * 16 = 176.
  3. y will be 12 after the calculation finishes.

Upvotes: 4

owenrb
owenrb

Reputation: 535

The expression (++y * (y++ + 5)); will be placed in a stack something like this:

1. [++y]
2. [operation: *]
3. [y++ + 5] // grouped because of the parenthesis

And it will be executed in that order, as result

1. 10+1 = [11] // y incremented 
2. [operation: *]
3. 11+5 = [16] // y will only increment after this operation

The the expression is evaluated as

11 * 16 = 176

Upvotes: 24

Marko Topolnik
Marko Topolnik

Reputation: 200246

First y++ + 5 will be executed because of the precedence of the innermost parentheses

Precedence and evaluation order are not the same thing. All binary expressions except the assignment expression are evaluated left-to-right. Therefore y++ is evaluated before the parenthesized expression on the right.

Upvotes: 14

Related Questions