File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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
Author

postfix increment

Anonymous
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++;
System.out.println(i);
Since the output is 0, does this mean that the increment in this particular case is useless?
Michael Zhao
Greenhorn

Joined: Sep 09, 2000
Posts: 2
this topic has been discussed here :
http://www.javaranch.com/ubb/Forum24/HTML/003185.html
Anonymous
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
      hello,
      i++//here ++ is a postfix operator.
      i.e., first the operand is evaluated and later incremented.
      bye


      http://www.skillfox.com Home of Java Skills SCJP 5.0, SCBCD, SCEA mock exams
      kiran k
      Greenhorn

      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...
      bye
      robl
      Greenhorn

      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: http://aspose.com/file-tools
       
      subject: postfix increment
       
      Similar Threads
      Output of this...........?How you got that?
      Doubt in the output of this program.
      a question on operator precedence
      Need Explanation of unpredicted output even if methods are synchronized
      Increment Test