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 Evaluating arithmetic expressions involving method calls 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 "Evaluating arithmetic expressions involving method calls" Watch "Evaluating arithmetic expressions involving method calls" New topic
Author

Evaluating arithmetic expressions involving method calls

Brian Joseph
Ranch Hand

Joined: May 16, 2003
Posts: 160
What are the rules to evaulating expressions that involve method calls? Do you just evaulate left to right and evaluate the methods as you read them?

Answer: 1,0
I figured 0,0 because I didn't think the ++ would take effect until after the addition was completed.
Alton Hernandez
Ranch Hand

Joined: May 30, 2003
Posts: 443

STEP 1: i++ is evaluated first because of associativity, and because postfix operations has higher precedence.
The result of the expression is still 0 because under JLS(15.14.1)

The value of the postfix increment expression is the value of the variable before the new value is stored.


STEP 2: m(i) is evaluated next. However, the value of i at this point is the incremented i. m(i) will print "1" but returns "0".
STEP 3. Finally, addition is performed, which would look something like this:
i = <result in Step 1> + <result in Step 2>
= 0 + 0
i = 0

If you where to interchange their positions like this:

the result would be different.
Brian Joseph
Ranch Hand

Joined: May 16, 2003
Posts: 160
Thanks, I think I got a handle on it. I now evaluate the expressions left to right and it helps to write down the intermediate expression as you did.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Evaluating arithmetic expressions involving method calls