The following works
float a=3;
but the following doesn't:
Float a=3;
Shouldn't 3 be automatically promoted to float (as widening conversions don't require an explicit cast) and then Boxed to Float type ?
Is it because of a rule I read in Khalid Mogul's Java book ?
Widening conversions can't be followed by any boxing conversions
The reason why Float a=3; won't work is because the compiler wraps the 3 into it's Integer object (in essence, the compiler does this: Float a = new Integer(3); and that's already a compiler error). Float object isn't and Integer object (even though they come from the same Number object).
The following works:
Number a = 3;
which in essence is translated by the compiler as:
Number a = new Integer(3);
or as Joachim Sauer mentioned,
Number a = Integer.valueOf(3);
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With