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.
I was mistaken about the order of precedence and order of evaluation.
This article helped me to further understand the answers provided.
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-- .
Yes, Java follows the standard arithmetic order of operations.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With