aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes post++ Operator: Doudt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "post++ Operator: Doudt" Watch "post++ Operator: Doudt" New topic
Author

post++ Operator: Doudt

Suren Babu
Greenhorn

Joined: Oct 23, 2000
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.
Advance Thanks...
Amit Tyagi
Ranch Hand

Joined: Oct 18, 2000
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: post++ Operator: Doudt