• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

postfix increment

 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello. Can someone please tell me why the following code yields an output of 0 instead of 1?
int i = 0;
i = i++;
System.out.println(i);
Since the output is 0, does this mean that the increment in this particular case is useless?
 
Michael Zhao
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this topic has been discussed here :
http://www.javaranch.com/ubb/Forum24/HTML/003185.html
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When the assignment statement executes:
  • <code>i++</code> is evaluated.
    • first, the value of this expression is determined to be <code>0</code>
    • then, <code>i</code> is incremented. <code>i</code> is now <code>1</code>.
    • Finally, the value of the expression (<code>0</code>) is assigned to <code>i</code>. <code>i</code> is now <code>0</code>


    • [This message has been edited by jply (edited September 09, 2000).]
  •  
    anil kuchana
    Ranch Hand
    Posts: 404
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    hello,
    i++//here ++ is a postfix operator.
    i.e., first the operand is evaluated and later incremented.
    bye
     
    kiran k
    Greenhorn
    Posts: 3
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    the form of increment is post increment;
    which means the expression is evaluated first and then the incrementation is performed.
    hope u got it...
    bye
     
    robl
    Greenhorn
    Posts: 25
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    I would cahracterize this one as a bug in the JVM.
    I understand why this occurs, but this is not the expected result.
    You should not have to think about how the compiler does its work to determine what the answer will be.
    The operator is posfix and nobody would expect the result to be 0 when it prints.
    Anyone agree or disagree?
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic