programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

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

Sam Lanza
Greenhorn
Posts: 17
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
Have a look at the following page in the JavaRanch FAQ:
Post Increment Operator And Assignment

Sam Lanza
Greenhorn
Posts: 17
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
Ooops! Didn't see your post there, Jesper. Thanks for the help!

Ilja Preuss
author
Sheriff
Posts: 14112
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
The difference between x=x++; and x++; is...

One.

 Did you see how Paul cut 87% off of his electric heat bill with 82 watts of micro heaters?