wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Postfix Operator evaluation Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Postfix Operator evaluation" Watch "Postfix Operator evaluation" New topic
Author

Postfix Operator evaluation

Chris Allen
Ranch Hand

Joined: Feb 01, 2003
Posts: 127
I was reading a separate post with postfix operators and have some confusion on the evaluation of postfix operators. For example:

This will print out j=0. I understand why this occurs as the value of j is incremented AFTER the assignment occurs. Now consider the next piece of code:


This will print out j=1. In this case the increment has occurred BEFORE the assignment occurs.

Can it be said that when there are more operations than just a single postfix operator that the postfix will be applied to the variable and a left to right evaluation occurs?
(Example: the above statement j = j++ + j turns into:
j = (j + 1) + 0
j = 1 + 0
Thus: j=1
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
This is all about evaluation of operands. Let me explain exactly what is happening and you can draw your own conclusions.

Here's our line of code:



In order to evaluate this expression, we must first evaluate operands, from left to right. The first operand we evaluate is j++. As you already know, this operand evaluates to 0 but, as a side-effect, j is incremented to 1. We now have this:



Now, we evaluate the next operand, which is just j. At this point, j is 1 so our expression evaluates to this:



Obviously, that expression assigns the value of 1 to j.


SCJP Tipline, etc.
Chris Allen
Ranch Hand

Joined: Feb 01, 2003
Posts: 127
Thanks. I like the method you use to break out the values (tracking the value of the variable as a comment on the right side of the expression) as the order is extremely important. I changed the example slightly and got different results which only made sense once I used your method of tracking the value. For example:



But if you switch the order of the operands to:

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Postfix Operator evaluation
 
Similar Threads
Java variables..strange!!
Khalid M Operator and Assigment question
Dissecting the post-fix operator
why different outputs in c++ and java!?
Post Increment