Why the typecasting of Wrapper Float does not works in java for Wrapper Integer type.
public class Conversion {
public static void main(String[] args) {
Integer i = 234;
Float b = (Float)i;
System.out.println(b);
}
}
An Integer
is not a Float
. With objects, the cast would work if Integer
subclassed Float
, but it does not.
Java will not auto-unbox an Integer
into an int
, cast to a float
, then auto-box to a Float
when the only code to trigger this desired behavior is a (Float)
cast.
Interestingly, this seems to work:
Float b = (float)i;
Java will auto-unbox i
into an int
, then there is the explicit cast to float
(a widening primitive conversion, JLS 5.1.2), then assignment conversion auto-boxes it to a Float
.
You are asking it to do too much. You want it to unbox i, cast to float and then box it. The compiler can't guess that unboxing i would help it. If, however, you replace (Float) cast with (float) cast it will guess that i needs to be unboxed to be cast to float and will then happily autobox it to Float.
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