Uttara Rishis contribution concerning the increment operator includes an aspect of operator behavior I discussed with a colleague a few weeks ago: Let "i" be an integer variable; how to predict the outcome of "i++ + ++i" with respect to Java?
According to Les Hattons "Safer C" (ISBN 0077076400) "in the example a*(f()+g()) although the addition is done before the multiplication, the order in which f() and g() are evaluated is undefined"; see subsection 2.8.2 "Evaluation order and precedence" on page 71 near the bottom.
Assume, that this C behavior applies to Java, we can't tell about the result of "i++ + ++i". Set "i=0". If "i++" is evaluated before "++i", the result is 0+1=1. If "++i" is evaluated first, the result is 1+1=2. Bottom line: We must not use expressions like "i++ + ++i" in our code.
This reply is intended to be both a thought-provoking impulse and a question: Does Java behave the same way like C? Could I ask you to provide a reference where this is declared officially, in either case? Can the compiler be invoked in order to detect situations like this and print a warning?
Is this kind of question likely to appear on the test??
Joined: Jun 03, 2007
Hello Tim, Dear Ranch People
I don't know if we should expect a question like this on the exam, though it's nasty enough, isn't it? But I don't want to blame the exam preparation commitee. ;-) A question like this might be discussed in an "Exam watch" box in Chapter 4, "Operators" in Kathie Sierras and Bert Bates SCJP book. I'll have a look later. Perhaps there's is a member of the committee around who can help us out here.
Thank you very much for your quick reply and the link to the language specification. :-) Unless I now know that evaluating the operands is deterministic, I thought both cases to make sense, i.e. (a) that Java "inherits" the unpredictable behavior from C as well as (b) that the Java creators defined an evaluation order, since brief notation may improve readability under complex circumstances like certain algorithms, e.g. in numerical mathematics.
You might feel that I overestimate that topic. But now I have an answer for a problem I worried about for a long time. Last but not least, I am a Java greenhorn and I would take years if not decades to sift through the shoreless documentation. Again, thanks a lot; I take your attention and helpfulness as a good example. :-)
Way back before the 1.4 days you would see questions like this on the exam. You *might* (but I don't think so). get one question like that on the 1.4 exam, but 1.5 and 6 won't go any further than the difference between ++x and x++.
Spot false dilemmas now, ask me how!
(If you're not on the edge, you're taking up too much room.)