Win a copy of Functional Reactive Programming this week in the Other Languages forum!

cast of NaN

cyril vidal
Ranch Hand
Posts: 247
Dear all,
Question 8 of dan's mock exam about primitive conversion:

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?
Cyril.

Damien Howard
Ranch Hand
Posts: 456
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.

Ranch Hand
Posts: 1873
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