Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# post++ Operator: Doudt

Suren Babu
Greenhorn
Posts: 27
The following program prints 0, i thought it will print 1.
class Test {
public static void main(String []args) {
int x=0;
x=x++;
System.out.println(x);
}
}
But the following program prints as expected...
class Test {
public static void main(String []args) {
int x=0;
x++;
System.out.println(x);
}
}
Could some body explain in detail what is happening in detail.

Amit Tyagi
Ranch Hand
Posts: 52

Hi,
The following program is prints 0 that's right.
Your being getting confused is also right...Its happens with every body in the starting
now see......
in your first prog.
class Test {
public static void main(String []args) {
int x=0;
x=x++; //Read like this x=x=(x+1) Here the operator is
postfix...thats why first it will assign the original valur of x(In your case x =0)to the
left side of x...and then it will increment the x by
Understand like this y = x = x+1;It will give x = 0 to y and then x itself will become 1; try to imagine y will be leading with value 0 and x trailing with 1;, in your case both x .. so two "x" are moving. so when ever you ask for value of x it will always print x =0; If you put for loop... in the next iteration first x will become 1 and trailing x will become 2....
x=x+1
.
.
.
.
x= x =0;///
System.out.println(x);
}
}
But in the following program ............here no y so only x will be carrying the value of 1;;; same as above. ..
class Test {
public static void main(String []args) {
int x=0;
x++;// The meaning is x = x+1...
System.out.println(x);
}
}

I am not sure about my explaining ability. But I always talk in the layman language....Hope it will solve your purpose
Amit