This week's book giveaway is in the Java 8 forum.
We're giving away four copies of Java 8 in Action and have Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Need help with a++/b-- expression Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Need help with a++/b-- expression" Watch "Need help with a++/b-- expression" New topic
Author

Need help with a++/b-- expression

Sarikaa Bhatnagar
Greenhorn

Joined: May 10, 2005
Posts: 26
HI,

Can someone pls help me with this.
int a =8;
int b=3;
float f = (float)a++/b--;

correct ans is 2.66 and not 4.5. As per the operator precedence ++ and -- shd be evaluted first the / ?

Thanks,
Sarika.
ahmed yehia
Ranch Hand

Joined: Apr 22, 2006
Posts: 424
Sarikaa Bhatnagar
Greenhorn

Joined: May 10, 2005
Posts: 26
HI,

my ques is why ++ and -- are not evaluated first when as per operator precedence rule ++ adn -- takes precedence over / operator. So why the division happend 8/3 and not 9/2

thanks,
sarika.
ahmed yehia
Ranch Hand

Joined: Apr 22, 2006
Posts: 424

So why the division happend 8/3 and not 9/2

Because you are using the postfix increment operator, the variable is used in the expression then incremented.. Try the prefix version i.e ++a
Vlado Zajac
Ranch Hand

Joined: Aug 03, 2004
Posts: 245
Originally posted by Sarikaa Bhatnagar:
HI,

my ques is why ++ and -- are not evaluated first when as per operator precedence rule ++ adn -- takes precedence over / operator. So why the division happend 8/3 and not 9/2

thanks,
sarika.


The ++ and -- are evaluated first but the value of a++ is 8 and value of b-- is 3.

The value of x++ is the old value of x.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Need help with a++/b-- expression
 
Similar Threads
Is This a Widening or an Upcast?
is this a legal overriding method?
doubt
Overload
Floats