Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

post-increment question

 
Kelly Walker
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2676
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
<font+=0>



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
 
Marcellus Tryk
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
Tod
 
Kelly Walker
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3695
IntelliJ IDE Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's another good explination.
http://www.javaranch.com/ubb/Forum33/HTML/002527.html
[This message has been edited by Mike Curwen (edited June 11, 2001).]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic