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 operator precedence question 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 "operator precedence question" Watch "operator precedence question" New topic
Author

operator precedence question

Atif Faridi
Greenhorn

Joined: Nov 16, 2002
Posts: 7
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

Joined: Nov 16, 2002
Posts: 7
Posting Errata:
The second sentence of Step 2 of my solution should read:
Evaluating ++k first yields ...
Atif
Abu Yoosuf
Ranch Hand

Joined: Nov 14, 2002
Posts: 33
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

Joined: Oct 14, 2002
Posts: 8829
    
    5
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.


Spot false dilemmas now, ask me how!
(If you're not on the edge, you're taking up too much room.)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: operator precedence question