Dear all, Question 8 of dan's mock exam about primitive conversion:
ANswer : false, false, true. For the two first answers, the key is to know that before to be casted as short type, a float type has to be casted into an int one. At first glance, it can appear logical. But what about the third answer, deduced from the fact that apparently, narrowing cast of Float.NaN or Double.NaN gives 0 as result? Is there a reason for that or is it just a rule we have to learn? Thanks in advance for your answer, Cyril.
SCJP 1.4, SCWCD, SCBCD, IBM XML, IBM Websphere 285, IBM Websphere 287
Joined: Apr 01, 2003
This is just a guess. Since NaN is really just a group of bits agreed upon to represent NaN, I would imagine that the agreed upon bit value is actually some sort of fractional value (0.1243...) , and since when you convert float and doubles to integral values, the fractional parts are just truncated off, NaN would become 0, assuming I'm making a correct assumption about NaNs representational value. For the sake of the exam, I would just remember that it casts to 0, although I doubt it will be on the exam. From what people have told me you can feel confident that K&B's book is inclusive of what you really need for the exam.
Joined: Nov 04, 2001
u can read java.lang.Float API and see what it has to say for NaN, "The Not-a-Number (NaN) value of type float. It is equal to the value returned by Float.intBitsToFloat(0x7fc00000)" regards maulin
Logical speculation. NaN is produced calculating ridiculous values. Calculation actually produces indeterminate value �Not-a-Number� when zero is divided. float f = (float)(0.0 / 0.0); System.out.print(f); When cast applied to �Not-a-Number� in this case (short), we ask the compiler to give us a number from something that�s Not-a-Number. I think the compiler laughs at this point, and gives us the most logical number 0. Cyril, I don�t think there's even a remote chance to see this question on the scjp exam.