Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 771
Stein121 Avatar asked Aug 25 '16 11:08

Stein121


People also ask

What is the correct order of operator precedence?

The logical-AND operator ( && ) has higher precedence than the logical-OR operator ( || ), so q && r is grouped as an operand. Since the logical operators guarantee evaluation of operands from left to right, q && r is evaluated before s-- .

Does Java go by order of operations?

Yes, Java follows the standard arithmetic order of operations.


1 Answers

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.

like image 194
Bathsheba Avatar answered Nov 12 '22 00:11

Bathsheba