SCJP, SCWCD, SCBCD
K. Tsang CEng MBCS PMP PMI-ACP OCMJEA OCPJP
SCJA
When I die, I want people to look at me and say "Yeah, he might have been crazy, but that was one zarkin frood that knew where his towel was."
W. Joe Smith wrote:This still looks funny to me. If I did myVal = myVal++, I know that myVal would be assigned the value for myVal then the increment happens. But shouldn't the increment increase the value of myVal, which would then be outputted?
K. Tsang CEng MBCS PMP PMI-ACP OCMJEA OCPJP
SCJA
When I die, I want people to look at me and say "Yeah, he might have been crazy, but that was one zarkin frood that knew where his towel was."
K. Tsang wrote:Suppose you have variable i. And you do i++ vs ++i. What's the difference?
i++ is assign to i then increment
++i is increment then assign back to i
So say i=0 to start with.
This also goes for i-- and --i
SCJP, SCWCD, SCBCD
Jisha Anand wrote:If the case was:
int myVal = 1;
int x = 1;
myVal = x++;
System.out.println("MYVAL: "+myVal+" "+"X: "+x);
The result will be:
MYVAL: 1 X: 2
My doubt is why doesn't the increment happen for myVal in a similar manner in the previous code?
K. Tsang CEng MBCS PMP PMI-ACP OCMJEA OCPJP
Campbell Ritchie wrote:When you haveyou set the value of 1 in i. Now, i++ increases the value of i by 1, before anything else happens, but it has its own value as well. So even though the value of i is now 2, the value of i++ as a whole is still 1, the old value. So writingtakes the value of i++ which we have already seen is 1, and applies that value to i. This happens last, so the value of 2 vanishes into cyber-limbo never to be seen again.
SCJP, SCWCD, SCBCD
K. Tsang wrote:
So why myVal is not 2? Because x assigns itself (a 1) to myVal then increment (x) itself.
SCJP, SCWCD, SCBCD
Henry Wong wrote:This issue is also explained in one of the JavaRanch FAQs.
http://faq.javaranch.com/java/PostIncrementOperatorAndAssignment
Henry
SCJP, SCWCD, SCBCD