On the final line, where you compare a==b
, the value of a
is being implicitly promoted to double before the comparison. So, in effect, what is really being evaluated is (((double)a)==b)
which, of course, evaluates true, since b
was initialized by casting a
as double in the first place.
In other words, the last boolean expression (a==b)
asks:
is (some float value converted to a double)==(the same float value converted to a double somewhere else)
and the answer is : yes.
UPDATE: a commenter below made a good point: when a
is promoted to double, the stored numeric value does not actually change, even though it appears to because a different value is printed. The issue is with how floating point numbers are stored; without making this answer WAAAY too long and wading in past my depth, what you need to know is that some simple decimal values cannot be perfectly represented in binary floating point form, no matter how many digits you have (just like you can't perfectly represent 1/3
in base 10 without an infinite number of 3s, as in 0.333333...), so when you assign one of these values using float (a 32-bit representation of a floating point number) and then you convert it to a double (a 64-bit representation) and then use println
to display the value of that number, you may see more digits.
The println
method displays the shortest string of decimal digits that convert to the same float (or double) value the computer sees internally. Although the same numerical value is passed as argument in the first two calls to println
in your example, the double
type has more precision so println
needs to print more digits to show “the shortest string of decimal digits that would convert to (double)99999.99F
”. If your example had been 9999.50, both numbers would have printed the same, because binary numbers can represent 1/2
just fine.
NOTE: I am not even close to an expert on floating point numbers; you should check out (http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) if you want a deeper understanding of what is going on here.