Search code examples
javaoperator-precedence

Java order of precedence


I just came across a piece of code I find interesting (because I have never seen it as a question before in 2 years of programming)

int x = 5;
int y = 3;
int z = y + (y+=1) % 4 + (x-=2) / 3;
System.out.println(z);

The output is 4.

I am wondering why is the left most 'y' evaluated first instead of the '(y+=1)' which would then resulted in an output of 5. (in other words, why is the bracket not forcing the order of precedence?)

I am not sure what to search since searching 'java order of precedence' returns results that at best shows tricky examples of y++, ++y kind of questions or just the order of precedence table.

I tagged Java but I have tested this with C# and javascript so it is probably a general thing in programming.

Update

I was mistaken about the order of precedence and order of evaluation.

This article helped me to further understand the answers provided.


Solution

  • In short, the parentheses only apply to a particular term.

    The expression y + (y+=1) % 4 + (x-=2) / 3; can be rewritten as t1 + t2 + t3, with t1 standing for y, t2 for (y+=1) % 4, and t3 for (x-=2) / 3.

    Java always evaluates this from left to right, since the associativity of the binary operator + is from left to right. Hence t1 is the first term to be evaluated and so is done so with the unincremented value of y.