Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Precedence and Associativity code snippet

586635Jun 6 2010 — edited Jun 9 2010
Look at this code snippet and assume the value of i is 2:
((k = (++i)) + (j = (2 * (++i))))
We have the pre-increment operator showing up twice and that operator is the highest level precedence in this example. Next in line as far as precedence goes is the multiply operator. So what I did was I went to the far right and raised i from 2 to 3
and then I figured since multiplication is the next in level of precedence I multiplied 3 * 2 to get 6.

But I guess that's not the correct way to evaluate this. The author said when you have two operators that are of the same level of precedence, Java uses associativity rules to "break the tie."

So I guess the correct thing to do is first increment i from 2 to 3 at the far left and then assign that to k.

I'm just a bit confused I guess. I thought step 1 would be to go to the far right and increment i from 2 to 3. Then step 2 would be to carry out the multiply operation.

Now the increment operator and the assignment operator are right associative. So the increment operator binds to variable i and the assignment operator binds to the result of incrementing i.

But I don't see the connection between being right associative and proceeding to evaluate expressions from left to right. I'm still not completely understanding why we evaluate the far left expression first and not do the far right one first.

Edited by: 357mag on Jun 6, 2010 7:46 PM

Edited by: 357mag on Jun 6, 2010 7:48 PM

Edited by: 357mag on Jun 6, 2010 7:49 PM
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jul 7 2010
Added on Jun 6 2010
23 comments
1,285 views