Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Post increment operator

 
subash chandar
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is the code that I tried:

int i = 10;
System.out.println(i);
i = i++;
System.out.println("i=" + i);

and i got the output as i=10

why the incremented value of i is not stored.

But if i change the stmt i=i++ to j=i++
i is incremented and the incremented value is stored in i
 
Mike Gershman
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if i change the stmt i=i++ to j=i++
i is incremented and the incremented value is stored in i

That is a good clue as to what is happening.

In the first case:
1. i (10) is copied onto the stack from its original location
2. the original i is incremented to 11
3. the copy of i (10) on the stack is copied into the original i
i is 10

In the second case:
1. i (10) is copied onto the stack from its original location
2. the original i is incremented to 11
3. the copy of i (10) on the stack is copied into j
i is 11
j is 10

now try this version:
i = ++i;
 
Carol Enderlin
drifter
Ranch Hand
Posts: 1364
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rats, Mike beat me to this. I was going to quote him from another post.

I put in a link to the post because some people seem to ask more questions even after the elegant answer.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic