File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Postfix Operator evaluation" Watch "Postfix Operator evaluation" New topic

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:
subject: Postfix Operator evaluation
It's not a secret anymore!