wood burning stoves*
The moose likes Beginning Java and the fly likes post-increment question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "post-increment question" Watch "post-increment question" New topic

post-increment question

Kelly Walker

Joined: Jun 08, 2001
Posts: 6
I've got a question about the post-increment operator. In the code below, I would have assumed that the final value of x would be 7, but it is 6. In statement 'x = x++;', why wouldn't x have been incremented after its current value was assigned to it? I'm probably overlooking something obvious, I know. Thanks...
( This issue came up when taking Marcus Green's 3rd SCJP mock exam - question 54 ).
int x = 5, y = 5;
y = x++;
System.out.println("x = " + x);
System.out.println("y = " + y);
x = x++;
System.out.println("x = " + x);
Matthew Phillips
Ranch Hand

Joined: Mar 09, 2001
Posts: 2676
In the case of a post-increment operator, the value of the expression takes place before the increment. Because of this fact the following pieces of code perform the same thing:

For readability, I prefer the first example. The way I remind myself what is happening is to think with parenthesis.
( int y = x )++ ;
The pre-increment operator will do the increment before the assignment. I hope this explanation helps.
Matthew Phillips

Matthew Phillips
Marcellus Tryk
Ranch Hand

Joined: May 31, 2001
Posts: 64
I think what you're asking is - why is x not equal to 7 since an increment operator has been applied twice. I thought this was very mysterious the first time I saw this example:
int x = 0;
x = x++;
x = x++;
x = x++;
What is the value of x? The answer is that x is equal to 0.
Here's what's going on:
1) The expression is evaluated. x++ is the original value of x (because we're using the post-increment operator).
2) x is incremented (So x is equal to the original value of x + 1).
3) The value of the expression is placed in x so x get's its original value back.
Hope this helps.
Kelly Walker

Joined: Jun 08, 2001
Posts: 6
Tod, yes that was my question. I also thought it was really strange when I saw it - I never would have guessed that Java would behave this way. I just assumed that the assignment would take place before x is incremented. But I guess that since the '++' operator has a higher precedence over assignment, then I suppose that it makes sense ( but it still seems a bit counter-intuitive to me). Thanks for both of your replies.
Mike Curwen
Ranch Hand

Joined: Feb 20, 2001
Posts: 3695

Here's another good explination.
[This message has been edited by Mike Curwen (edited June 11, 2001).]
I agree. Here's the link: http://aspose.com/file-tools
subject: post-increment question
Similar Threads
inc / dec Operations precedence
Be the JVM: what is the output
doubts getting exponentially INCREMENTed
++ again
associativity and precedence...prob..pls..help