File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Operator Precedence - Confused Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Operator Precedence - Confused" Watch "Operator Precedence - Confused" New topic

Operator Precedence - Confused

Tresa Antony

Joined: Jan 28, 2005
Posts: 5
Could you please help me understand whats happening here? Why does it print 0 and not 1?

Also, let

int a=1,b=5;

In the expression (a++ < b--) , does a++ and b-- happen first and then the 'less than' comparison?

Patrick Joseph

Joined: Jan 11, 2005
Posts: 11
i++ is postfix notation.

So i is incremented only after the original value of i is used in the expression i=i++;

Hope that explains it...
Joel McNary

Joined: Aug 20, 2001
Posts: 1824

First, evaluate the value of i. Store that on top of the stack. (0)
Next, increment i (through the post-fix operator). i now equals 1.
Now, perform the assignment. Assign i the value on top of the stack (0).

Now, i = 0.

Post-fix notation happens after the evaluation of the variable, but before the assignment.

Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
Mike Gershman
Ranch Hand

Joined: Mar 13, 2004
Posts: 1272
In the expression (a++ < b--) , does a++ and b-- happen first and then the 'less than' comparison?

Yes, but the comparison uses the original values of a and b.

Mike Gershman
SCJP 1.4, SCWCD in process
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
In my opinion, this is a terrible way to write code. As a rule of thumb, you should limit the number of side-effects (changes to values in variables) to one per line of code. I cannot think of any situation where "i=i++" would even be useful. Although, I could imagine where "a++ < b--" might be tempting, I would instead do something like this:

Of course, if the new values of a and b are needed in the body of the if statement, the increment and decrement would need to be inside the body rather than after it. However, the point is to separate these side-effects into separate statements. It will make the code much easier to read and maintain.

Keep Coding!


Java API Documentation
The Java Tutorial
I agree. Here's the link:
subject: Operator Precedence - Confused
It's not a secret anymore!