Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Evaluating arithmetic expressions involving method calls

 
Brian Joseph
Ranch Hand
Posts: 160
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 443
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Posts: 160
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic