• Post Reply Bookmark Topic Watch Topic
  • New Topic

What's the difference between x=x++; and x++;?  RSS feed

 
Sam Lanza
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've been playing around with iterations, and here's a strange situation I've bumped into:

1.) x = x++;
2.) x++;

Now, I know that in the first expression, x increments by 1 AFTER it assigns to x. So if x were initialized to 0, the first expression would produce 0 and the second expression would produce 1 as intended. However, if you would put the first expression into a loop, it just keeps printing 0s instead of incrementing. For some reason, it doesn't remember the value of x through each iteration. So it basically just acts like x=x. What gives? Here's the code I tested:

class WhileTest {
public static void main(String[] args) {
int x = 0;

while(x<10) {
x=x++;
System.out.println(x);
}
}
}

This just goes into a never-ending loop of 0s.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have a look at the following page in the JavaRanch FAQ:
Post Increment Operator And Assignment
 
Sam Lanza
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, I figured out my own question. DUH! The assignment of x++ to x trumps the value of x++. So basically, in each iteration, the value assigned (0) is coming back around to be iterated by x++. However, since x is not iterated until after the expression, x is always being assigned 0. Hehe. I'm a total NOOB!
 
Sam Lanza
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ooops! Didn't see your post there, Jesper. Thanks for the help!
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Sam Lanza:
I know that in the first expression, x increments by 1 AFTER it assigns to x.


You already found about it, but just to clearly speak it out: this assumption simply is false.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The difference between x=x++; and x++; is...

One.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!