aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Increment operator in assignment 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 "Increment operator in assignment" Watch "Increment operator in assignment" New topic
Author

Increment operator in assignment

Selvakumar Arumugam
Greenhorn

Joined: Dec 26, 2003
Posts: 2
Anybody please explain what is happening here?
--------------
int i =0;
i = i++;
i = i++;
i = i++;
System.out.println(i);
--------------
I was expecting i to be 3. But it's printing 0.
Vicken Karaoghlanian
Ranch Hand

Joined: Jul 21, 2003
Posts: 522
Hi Selvakumar and welcome to the ranch, the post increment operator always returns its old value then increment it.


- Do not try and bend the spoon. That's impossible. Instead, only try to realize the truth. - What truth? - That there is no spoon!!!
Thomas De Vos
stable boy
Ranch Hand

Joined: Apr 12, 2003
Posts: 425
The reason is that the ++ operator is a postfix operator.
You can read x++ also as x = x = (x+1)
This means that the value of x in your case 0 is first assigned to x and then incremented. The value is incremented after the assignment operation.
The second time around the value of i will be still 0 and then assigned first and incremented etc.


Try your free <a href="http://www.javacertificate.com" target="_blank" rel="nofollow">SCJP 1.4</a> certification centre.<br />Try your free <a href="http://www.j2eecertificate.com" target="_blank" rel="nofollow">SCWCD</a> certification centre.<br />Try your free <a href="http://www.ejbcertificate.com" target="_blank" rel="nofollow">SCBCD</a> certification centre.<br />Try your <a href="http://www.webspherecertificate.com" target="_blank" rel="nofollow">Websphere (Test 285) </a> certification centre.<br />Try your <a href="http://www.j2mecertificate.com" target="_blank" rel="nofollow">SCMAD</a> certification centre. (New)<br /> <br /><a href="http://blogs.javacertificate.com" target="_blank" rel="nofollow">Java/J2EE Certification Blogging</a>
Selvakumar Arumugam
Greenhorn

Joined: Dec 26, 2003
Posts: 2
Vicken and Thomas Thanks for the reply. I am clear about it.
Thanks!
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Increment operator in assignment