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 how is this possible??? 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 "how is this possible???" Watch "how is this possible???" New topic

how is this possible???

David Moore

Joined: Oct 10, 2000
Posts: 8
I hope this is not a stupid question.
Why does this code print 0?
public class test {
public static void main(String[] args) {
int i = 0;
i = i++;
i = i++;
i = i++;
William Brogden
Author and all-around good cowpoke

Joined: Mar 22, 2000
Posts: 13036
It has to do with the order in which expresions are evaluated. I believe it works out like this:
1. calculate where results go
2. get the value of the expression
3. increment i
4. store the value from 2 in the location from 1
(thus over-writing the incremented i)

author of:
kriti sharma
Ranch Hand

Joined: Feb 16, 2001
Posts: 160
David, always remember that there is some difference between the postfix and ur code there is postfix i.e. the value is incremented after it is being assigned to itself or to some other variable.had it been prefix (++i) the output would be 3.
hope i have cleared ur doubt.
David Moore

Joined: Oct 10, 2000
Posts: 8
When you say in line 3 increment i, it does not happen because
= is of higher presedence than ++, so the increment never happens because it's after i?
Manfred Leonhardt
Ranch Hand

Joined: Jan 09, 2001
Posts: 1492
Hi David,
The ++ operator has much higher percedence than assignment(=). Bill's steps are correctly ordered. The increment happens before (step 3) the assignment (step 4). Think of the postfix as using a special Java 'holding' area.
1. Place current value of i into holding area (move zero to holding area)
2. Increment current value of i (i now becomes 1)
3. Assign value in holding area to i (i now assigned zero)
Simple but effective,
ratul banji
Ranch Hand

Joined: Mar 15, 2001
Posts: 108
Hi all,
Just visit the folowing thread.
Same topic have been discussed there.
<marquee> Ratul Banerjee </marquee>
I agree. Here's the link:
subject: how is this possible???
It's not a secret anymore!