Java Priority

I just came across a piece of code that interests me (because I never saw it as a question before after 2 years of programming)

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

Output 4.

I am wondering why the left side of 'y' is first evaluated instead of '(y + = 1)', which then leads to pin 5. (in other words, why does the bracket not force the precedence order?)

I'm not sure what to look for, since a search for "java order of priorence" returns results that, at best, show complex examples of y ++, ++ y like questions or just the order of the priority table.

I tagged Java, but I tested it with C # and javascript, so this is probably common in programming.

Update

I made a mistake in the order of priority and the order of evaluation.

This article helped me understand the answers I received.

+6
source share
2 answers

In short, parentheses only apply to a specific term.

Expression y + (y+=1) % 4 + (x-=2) / 3; can be rewritten as t1 + t2 + t3 , << 22> 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 runs from left to right. Therefore, t1 is the first term to be evaluated, and therefore this is done with an uninformed value of y .

+11
source

All Articles