Take the 2-minute tour ×

What happens (behind the curtains) when this is executed?

int x = 7;
x = x++;

That is, when a variable is post incremented and assigned to itself in one statement? I compiled and executed this. x is still 7 even after the entire statement. In my book, it says that x is incremented!

share|improve this question
Thank-goodness this question was tagged Java and not C... –  user166390 Oct 27 '11 at 5:37
it's funnier if you write x += ++x –  fortran Oct 27 '11 at 9:41
What happens? Team leader will slap you. –  alxx Oct 27 '11 at 11:09
My rule: Always prefer ++i over i++, unless you need the latter one explicitly. –  Deqing Aug 20 '12 at 8:41
@lukas, I disagree. Post-increment operators have a definite use (and cannot always be replaced by pre-increment operators). For example, in simulating a stack pointer, or when iterating through an array. It is necessary when the pointer points to the first item unused or unprocessed (e.g. position 0). Pre-increment operators can be used if the pointer points to the last used or last processed item (much less useful). –  Stephen Chung Aug 20 '12 at 10:44

16 Answers 16

up vote 195 down vote accepted

x does get incremented. But you are assigning the old value of x back into itself.

x = x++;

x++ increments x and returns its old value. x = assigns the old value back to itself.

So in the end, x gets assigned back to its initial value.

share|improve this answer
Then, what will you say about x = ++x; –  Hisham Muneer May 2 '14 at 16:38
@HishamMuneer x gets incremented first before it's read in that case, so you end up with x + 1. –  Cupcake May 3 '14 at 3:01
@HishamMuneer It's too late. But I am putting it here because it may be helpful for some other people who will look in future. The best way to under stand this problem is looking at the assembly code created for x=x++ and x=++x. Please see the answer of Thinkingcap also. –  nantitv Apr 15 at 13:02
x = x++;

is equivalent to

int tmp = x;
x = tmp;
share|improve this answer
Lol, yay for recursive definitions. you probably should've done x=x+1 instead of x++ –  user606723 Oct 27 '11 at 13:12
@user606723: No. i meant the whole statement x = x++ , not just the post increment x++. –  Prince John Wesley Oct 27 '11 at 13:56
I don't think this is all that useful without further explanation. For instance, it's not true that x = ++x; is also equivalent to int tmp = x; ++x; x = tmp;, so by what logic can we deduce that your answer is correct (which it is)? –  kvb Oct 27 '11 at 17:53
even more clear it is in asm x=x++ = MOV x,tmp; INC x; MOV tmp,x –  forker Oct 27 '11 at 19:39
@forker: I think it would be clearer if you used assembly instructions that apply to the processor Michael is using ;) –  Carl Oct 27 '11 at 20:30

The statement:

x = x++;

is equivalent to:

tmp = x;   // ... this is capturing the value of "x++"
x = x + 1; // ... this is the effect of the increment operation in "x++" which
           //     happens after the value is captured.
x = tmp;   // ... this is the effect of assignment operation which is
           //     (unfortunately) clobbering the incremented value.

In short, the statement has no effect.

The key points:

  • The value of a Postfix increment/decrement expression is the value of the operand before the increment/decrement takes place. (In the case of a Prefix form, the value is the value of the operand after the operation,)

  • the RHS of an assignment expression is completely evaluated (including any increments, decrements and/or other side-effects) before the value is assigned to the LHS.

Note that unlike C and C++, the order of evaluation of an expression in Java is totally specified and there is no room for platform-specific variation. Compilers are only allowed to reorder the operations if this does not change the result of executing the code from the perspective of the current thread. In this case, a compiler would be permitted to optimize away the entire statement because it can be proved that it is a no-op.

In case it is not already obvious:

  • "x = x++;" is almost certainly a mistake in any program.
  • The OP (for the original question!) probably meant "x++;" rather than "x = x++;".
  • Statements that combine auto inc/decrement and assignment on the same variable are hard to understand, and therefore should be avoided irrespective of their correctness. There is simply no need to write code like that.

Hopefully, code checkers like FindBugs and PMD will flag code like this as suspicious.

share|improve this answer
As a side note, OP, you probably mean to just say x++ instead of x = x++. –  Jonathan Newmuis Aug 20 '12 at 7:29
Correct, but maybe emphasize that the increment happens post right-hand expression evaluation, but pre assignment to left hand side, hence the apparent "overwrite" –  Bohemian Aug 20 '12 at 7:31
that seems like one of those high-school programming twisters... good to clear up your basics! –  kumar_harsh Aug 20 '12 at 10:11
@Alberto - bytecodes are minimally optimized. The significant optimizations are all done by the JIT compiler. OTOH, this may be a situation which doesn't get optimized. The statement is really an obscure way of doing nothing, and is unlikely to occur in production code. A specific optimization for this case would a waste of effort, and a waste of JIT compiler time. –  Stephen C Aug 25 '12 at 8:21
Just a FYI: this was originally posted to a different question, which was closed as a duplicate of this one and has now been merged. –  Shog9 Sep 6 '12 at 22:43
int x = 7;
x = x++;

It has undefined behaviour in C and for Java see this answer. It depends on compiler what happens.

share|improve this answer
No it does not depend on the compiler according to the answer you quoted - please edit - -1 for now –  Mr_and_Mrs_D Sep 29 '13 at 17:11
@Mr_and_Mrs_D Then it depends on what? –  Mac Jun 4 '14 at 6:32
It's undefined behavior_only for C_. Even so saying it depends on the compiler is misleading - it implies the compiler should kind of specify this behavior. I revert my vote but consider editing your answer - edit: oops I can't - you have to edit it first :D –  Mr_and_Mrs_D Jun 4 '14 at 13:52

A construct like x = x++; indicates you're probably misunderstanding what the ++ operator does:

// original code
int x = 7;
x = x++;

Let's rewrite this to do the same thing, based on removing the ++ operator:

// behaves the same as the original code
int x = 7;
int tmp = x; // value of tmp here is 7
x = x + 1; // x temporarily equals 8 (this is the evaluation of ++)
x = tmp; // oops! we overwrote y with 7

Now, let's rewrite it to do (what I think) you wanted:

// original code
int x = 7;

The subtlety here is that the ++ operator modifies the variable x, unlike an expression such as x + x, which would evaluate to an int value but leave the variable x itself unchanged. Consider a construct like the venerable for loop:


Notice the i++ in there? It's the same operator. We could rewrite this for loop like this and it would behave the same:


I also recommend against using the ++ operator in larger expressions in most cases. Because of the subtlety of when it modifies the original variable in pre- versus post-increment (++x and x++, respectively), it is very easy to introduce subtle bugs that are difficult to track down.

share|improve this answer

It's incremented after "x = x++;". It would be 8 if you did "x = ++x;".

share|improve this answer
If it is incremented after x = x++, then it should be 8. –  R. Martinho Fernandes Dec 1 '11 at 0:21

The incrementing occurs after x is called, so x still equals 7. ++x would equal 8 when x is called

share|improve this answer

When you re-assign the value for x it is still 7. Try x = ++x and you will get 8 else do

x++; // don't re-assign, just increment
System.out.println(x); // prints 8
share|improve this answer

because x++ increments the value AFTER assigning it to the variable. so on and during the execution of this line:


the varialbe x will still have the original value (7), but using x again on another line, such as

System.out.println(x + "");

will give you 8.

if you want to use an incremented value of x on your assignment statement, use


This will increment x by 1, THEN assign that value to the variable x.

[Edit] instead of x = x++, it's just x++; the former assigns the original value of x to itself, so it actually does nothing on that line.

share|improve this answer
This is just plain wrong. Have you even tried running it? –  R. Martinho Fernandes Dec 1 '11 at 0:17
what part is just plain wrong? –  josephus Dec 1 '11 at 2:42
The one that says it increments after assigning, and the one that says it will print 8. It increments before assigning, and it prints 7. –  R. Martinho Fernandes Dec 1 '11 at 2:43
if x is originally 7, System.out.println(String.valueOf(x++)); prints 7. you sure we're talking about the same programming language? –  josephus Dec 1 '11 at 2:47
Yes, I am. This ideone.com/kj2UU doesn't print 8, like this answer claims. –  R. Martinho Fernandes Dec 1 '11 at 2:50

What happens when int x = 7; x = x++;?

ans -> x++ means first use value of x for expression and then increase it by 1.
This is what happens in your case. The value of x on RHS is copied to variable x on LHS and then value of x is increased by 1.

Similarly ++x means -> increase the value of x first by one and then use in expression .
So in your case if you do x = ++x ; // where x = 7
you will get value of 8.

For more clarity try to find out how many printf statement will execute the following code

while(i++ <5)   
  printf("%d" , ++i);   // This might clear your concept upto  great extend
share|improve this answer

++x is pre-increment -> x is incremented before being used
x++ is post-increment -> x is incremented after being used

int x = 7; -> x get 7 value <br>
x = x++; -> x get x value AND only then x is incremented
share|improve this answer

According to Byte code obtained from the class files,

Both assignments increment x, but difference is the timing of when the value is pushed onto the stack

In Case1, Push occurs (and then later assigned) before the increment (essentially meaning your increment does nothing)

In Case2, Increment occurs first (making it 8) and then pushed onto the stack(and then assigned to x)

Case 1:

int x=7;

Byte Code:

0  bipush 7     //Push 7 onto  stack
2  istore_1 [x] //Pop  7 and store in x
3  iload_1  [x] //Push 7 onto stack
4  iinc 1 1 [x] //Increment x by 1 (x=8)
7  istore_1 [x] //Pop 7 and store in x
8  return       //x now has 7

Case 2:

int x=7; 

Byte Code

0  bipush 7     //Push 7 onto stack
6  iload_1  [x] //Push x onto stack
7  istore_1 [x] //Pop 8 and store in x
8  return       //x now has 8
  • Stack here refers to Operand Stack, local: x index: 1 type: int
share|improve this answer

So this means: x++ is not equal to x = x+1


int x = 7; x = x++;
x is 7

int x = 7; x = x = x+1;
x is 8

and now it seems a bit strange:

int x = 7; x = x+=1;
x is 8

very compiler dependent!

share|improve this answer
who said it was equal in first place? –  fortran Oct 27 '11 at 13:23
@fortran Well at several places we have read it, and even in starter books, the meaning is explained this way that: x++ means x=x+1. You can consider the following link for the same as one of the many answers explanation_link –  linuxeasy Oct 27 '11 at 13:44
If I were you I'd trash these books immediately xD In any case, it would be like (x = x + 1, x-1) in C, where comma separated expressions are allowed. –  fortran Oct 27 '11 at 15:52
@fortran: Well, in my decade-old copy of "The Java Programming Language, Third Edition" on page 159 it says ""The expression i++ is equivalent to i=i+1 except that i is evaluated only once". Who said it in the first place? James Gosling, it would appear. This portion of this edition of the Java spec is extraordinarily vague and poorly specified; I presume that later editions cleaned up the language to express the actual operator semantics more clearly. –  Eric Lippert Oct 27 '11 at 17:05
@fortran: by "except i is evaluated only once" the standard is attempting to convey that an expression like "M().x++" only calls M() once. A less vague and more accurate wording would emphasize that there is a difference between evaluating i as a variable to determine its storage location -- which is what is meant by "evaluated only once" here -- and reading or writing to that storage location -- either of which could be a reasonable but incorrect interpretation of 'evaluated'. Clearly the storage location has to be both read and written! –  Eric Lippert Oct 27 '11 at 18:02

I think this controversy can be resolved without going into code & just thinking.

Consider i++ & ++i as functions say Fun1 & Fun2.

If i=7;
i++ function(Fun1) returns 7, ++i function(Fun2) returns 8 (this everybody knows). Internally both the functions increment i to 8 , but they return different values.

So i = i++ calls the function Fun1. Inside the function i increments to 8, but on completion the function returns 7.

So ultimately 7 gets allocated to i. (So in the end i=7; is executed)

share|improve this answer

Post Increment operator works as follows:

  1. Store previous value of operand.
  2. Increment the value of the operand.
  3. Return the previous value of the operand.

So the statement

int x = 7;
x = x++; 

would be evaluated as follows:

  1. x is initialized with value 7
  2. post increment operator stores previous value of x i.e. 7 to return.
  3. Increments the x, so now x is 7
  4. Returns the previous value of x i.e. 7 and it is assigned back to x, so x again becomes 7

So x is indeed increased but since x++ is assigning result back to x so value of x is overridden to its previous value.

share|improve this answer

x = x++;

This is the post-increment operator. It should be understood as "Use the operand's value and then increment the operand".

If you want the reverse to happen i.e "Increment the operand and then use the operand's value", you must use the pre-increment operator as shown below.

x = ++x;

This operator first increments the value of x by 1 and then assigns the value back to x.

share|improve this answer

protected by Stephen C Mar 9 '14 at 10:07


Would you like to answer one of these unanswered questions instead?
