• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Post increment

 
Subhash Daga
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Inc{
public static void main(String argv[]){
int i = 0;
i=i++; // line 4
System.out.println(i);
}
}
The output is 0.
At line 4, i is assigned 0 which is fine. But after that I expected i to increment and become 1. But why not so?
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Welcome to JavaRanch!
All the side effects of evaluating the right-hand-side occur before the assignment is done. So here's what happens:
  • The value of "i" (0) is stored on the stack.
  • "i" is incremented, becoming 1. Now the RHS is completely evaluated.
  • The stored value is popped off the stack and assigned to "i", completing the statement.


  • So this is why "i" ends up as 0.
     
    Michael Morris
    Ranch Hand
    Posts: 3451
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    There are two incrementers in Java, the post-incrementer or i++ and the pre-incrementer or ++i. The difference between the two is one returns the value before incrementing (post) and the other returns the value after incrementing (pre). So what happens in your example is, i is incremented to 1, but returns its previous value of 0 so the result is i remains 0. If you use i = ++i it will do as you expect. Try this:

    That should print 0 on the first line and 1 on the next. If you change to the pre-imcrement operator, both lines should print 1.
     
    Davy Kelly
    Ranch Hand
    Posts: 384
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Subhash.
    i++ increments after ++i increments before.
    the above posts expalin it well.
    Armed with this information you could try to take you knowledge to another level.

    Davy
    [ February 22, 2004: Message edited by: Davy Kelly ]
    [ February 22, 2004: Message edited by: Davy Kelly ]
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic