First, let me reiterate what Phil said: this is definitely beyond the scope of what you need to know for the exam. Partly because it depends on obscure details, and partly because it would require a lot more careful calculation than is expected for
SCJP problems. So if you read this
thread and still don't understand the problem, and you just want to do well on the test: don't worry about it. Just move on.
But if you want more detail anyway...
[B][Phil]:
The results are identical: 41dfffffffc00000.[/B]
That's because of a cut-and-paste error on the last line of the code above. The results aren't really identical.
[B][Phil]:
I was surprised to see that both comparisons result in false![/B]
Well, that's because the equality operator is symmetric. x == y if and only if y == x.
Vishal: what's actually happening here is that when we convert from an integral type to a floating-point type, some roundoff may occur. This means that the value you get may not be exactly what you were expecting, and == may return unexpected results. It doesn't
always return strange results, as some integral numbers are already equal to the closest number they would round to in floating-point. And sometimes both left and right sides of the equation get rounded to the
same floating-point number. Figuring out exactly how and when this happens requires a good understanding of exactly how floating-point numbers are represented in
Java; I'm not going to go into it in detail since it's definitely beyond the scope of the exam. For our purposes, it's enough to say that it appears to happen more or less at random.
This is really just a special case of a general principle when dealing with floating point: they often aren't exactly what you expect them to be. Writing code that depends on exact equality is usually a bad idea where floating-point numbers are concerned. This is why, for example,
JUnit has no assertEquals(float, float) method - but it has an assert(float, float, float) where the third parameter describes the maximum allowable difference between the first two parameters. (You could set this third parameter to zero I suppose, but it's probably a bad idea nless you're sure you know what you're doing.) Just remember that == is unreliable for floating point - that's all you really need to know here.
[ August 07, 2005: Message edited by: Jim Yingst ]