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 postfix increment 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 "postfix increment" Watch "postfix increment" New topic

postfix increment

Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Hello. Can someone please tell me why the following code yields an output of 0 instead of 1?
int i = 0;
i = i++;
Since the output is 0, does this mean that the increment in this particular case is useless?
Michael Zhao

Joined: Sep 09, 2000
Posts: 2
this topic has been discussed here :
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
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

      Joined: Sep 08, 2000
      Posts: 404
      i++//here ++ is a postfix operator.
      i.e., first the operand is evaluated and later incremented.
      bye Home of Java Skills SCJP 5.0, SCBCD, SCEA mock exams
      kiran k

      Joined: Sep 11, 2000
      Posts: 3
      the form of increment is post increment;
      which means the expression is evaluated first and then the incrementation is performed.
      hope u got it...

      Joined: Aug 26, 2000
      Posts: 25
      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?
      I agree. Here's the link:
      subject: postfix increment
      It's not a secret anymore!