File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Post increment Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Post increment" Watch "Post increment" New topic

Post increment

Subhash Daga

Joined: Feb 21, 2004
Posts: 2
public class Inc{
public static void main(String argv[]){
int i = 0;
i=i++; // line 4
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

Joined: Jul 08, 2003
Posts: 24195

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.

    [Jess in Action][AskingGoodQuestions]
    Michael Morris
    Ranch Hand

    Joined: Jan 30, 2002
    Posts: 3451
    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.

    Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher
    Davy Kelly
    Ranch Hand

    Joined: Jan 12, 2004
    Posts: 384
    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.

    [ February 22, 2004: Message edited by: Davy Kelly ]
    [ February 22, 2004: Message edited by: Davy Kelly ]

    How simple does it have to be???
    subject: Post increment
    It's not a secret anymore!