javaoperatorsoperator-precedence

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?


Solution

  • 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