aspose file tools*
The moose likes Beginning Java and the fly likes Post increment operator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Post increment operator" Watch "Post increment operator" New topic
Author

Post increment operator

subash chandar
Greenhorn

Joined: Feb 07, 2005
Posts: 8
Here is the code that I tried:

int i = 10;
System.out.println(i);
i = i++;
System.out.println("i=" + i);

and i got the output as i=10

why the incremented value of i is not stored.

But if i change the stmt i=i++ to j=i++
i is incremented and the incremented value is stored in i
Mike Gershman
Ranch Hand

Joined: Mar 13, 2004
Posts: 1272
if i change the stmt i=i++ to j=i++
i is incremented and the incremented value is stored in i

That is a good clue as to what is happening.

In the first case:
1. i (10) is copied onto the stack from its original location
2. the original i is incremented to 11
3. the copy of i (10) on the stack is copied into the original i
i is 10

In the second case:
1. i (10) is copied onto the stack from its original location
2. the original i is incremented to 11
3. the copy of i (10) on the stack is copied into j
i is 11
j is 10

now try this version:
i = ++i;


Mike Gershman
SCJP 1.4, SCWCD in process
Carol Enderlin
drifter
Ranch Hand

Joined: Oct 10, 2000
Posts: 1364
Rats, Mike beat me to this. I was going to quote him from another post.

I put in a link to the post because some people seem to ask more questions even after the elegant answer.
 
Don't get me started about those stupid light bulbs.
 
subject: Post increment operator