• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why does it print 0??  RSS feed

 
Anoop Nair
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
int i =0;
i = i++;
System.out.println(i);

Why does it print 0 and not 1???
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you search around this forum, you'll find literally hundreds of threads over the years discussing exactly this question.

The key to the answer is that the value of the expression "i++" is the value of i before the increment. The code that actually executes for "i = i++" takes the following steps:

1) Store the original value of i on the Java stack; that's the value of the right-hand-side of the assignment
2) Increment the variable i (i becomes 1)
3) Pop the value off the stack and put it in i (i becomes 0 again).\

Note that if the assignment was something like

int i = 0;
int a = i++;

then after these two lines of code, "a" is zero, and "i" is 1. you should understand why at this point!
 
Larry Frissell
Ranch Hand
Posts: 82
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See this thread.
 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This subject comes up regularly. But,

Why did you expect to get 1 printed out in the first place?

There are two values you want to consider, the value of the variable i and the value of the expression i++.

The order of execution is something like this:
  • The value of i is initialised to 0.
  • The i++ is executed, which makes the value of i 1 and the value of i++ is the old value of i.
  • The = operator is executed, and i is assigned the value of the expression i++ which is 0
  • The value of i which is 0 is printed out.
  • QED

    Any JVM which prints out 1 should be rejected as faulty. The same ought to apply to C and C++ too; I think it also applies to C#.
     
    Ilja Preuss
    author
    Sheriff
    Posts: 14112
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Originally posted by Campbell Ritchie:
    The same ought to apply to C and C++ too; I think it also applies to C#.


    As far as I remember, for at least one of those languages, the result is actually undefined.
     
    Campbell Ritchie
    Marshal
    Posts: 56546
    172
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    It says in the C books that it is supposed to be the same, but every now and again somebody finds a C compiler which executes that and produces 1, so you are probably right that it is undefined in C.
     
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!