• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

operator precedence question

 
Atif Faridi
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In Mughal p56 Review Question 3.7, you are asked to evaluate the following expression with k initialized to 1:
++k + k++ + + k
The answer is 7 but I am confused as to how it is obtained. In the answer section Mughal says that it is evaluated as
((2) + (2) + (3))
I assume this means that we just evaluate each component of the expression from left to right. But doesn't this ignore operator precedence as indicated in Table 3.1 on page 42? Specifically,
... expression++ ...
++expression ... +expression ...

I reached the same answer evaluating as follows:
1) postfix ++ operator has highest precedence so k++ is evaluated first so we have
(++k + 1 + + k) and k=2 now
2) prefix ++ operator and unary + operator have the same precedence so evaluate left to right. Evaluating k++ first yields
(3 + 1 + + k) and k=3 now
3) Finally evaluating +k yields
(3 + 1 + 3) = 7
Who is correct? Why? Thank you.
Regards,
Atif
 
Atif Faridi
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Posting Errata:
The second sentence of Step 2 of my solution should read:
Evaluating ++k first yields ...
Atif
 
Abu Yoosuf
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Check this out
http://www.coderanch.com/t/190825/java-programmer-SCJP/certification/Array
[ November 16, 2002: Message edited by: Abu Yoosuf ]
 
Bert Bates
author
Sheriff
Posts: 8898
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
back again with my same old advice...
the scjp 1.4 will not be looking for this kind of knowledge - if you're curious about this precedence stuff , well great - but if you're studying for the test - focus on other areas - this stuff isn't on the test.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic