File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Postfix operation 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 "Postfix operation" Watch "Postfix operation" New topic
Author

Postfix operation

Vidyavathi saravanan
Ranch Hand

Joined: Sep 24, 2004
Posts: 34


This is one of Dans' question. The answer is 5 as per ( a=1+2+2).
My doubt is what happened to the postfix operation a++. ( Is it not correct that this postfix makes a as 6.
Chris Allen
Ranch Hand

Joined: Feb 01, 2003
Posts: 127
Originally posted by Vidyavathi saravanan:


This is one of Dans' question. The answer is 5 as per ( a=1+2+2).
My doubt is what happened to the postfix operation a++. ( Is it not correct that this postfix makes a as 6.


The way I got to the answer was as follows:
int a=1;a += ++a + a++;
then: a += (2) + a++;
then: a += (2) + (2); ->a will be incremented to 3 once the statement is finished
then: 1 += (2) + (2);
equals: a=5 (assign 5 to the value of a)

Remember that the postfix operator only takes effect AFTER the statement is processed and as such, is not involved in the calculation of this line. Since the value of a has already been set to 5, the effect is that the value of a is incrmented but it is not assigned to a and basically is lost.

Think of it this way:
We have already assigned the value of the variable a so you can increment it, but it will be ignored as the assignment is already done.
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
What actually happens is the following:

a += ++a + a++; (a==1)
a = a + ++a + a++; (a==1)
a = 1 + ++a + a++; (a==1)
a = 1 + a + a++; (a==2)
a = 1 + 2 + a++; (a==2)
a = 3 + a++; (a==2)
a = 3 + 2 [need to increment a now]; (a==2)
a = 3 + 2; (a==3)
a = 5; (a==3)
(a==5)

That is, a does get incremented, but before the assignment of the expressions value happens.

Does that help?


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Postfix operation