Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Wrapper Integer to Float conversion not possible in java

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);

    }
}
like image 442
Ankit Zalani Avatar asked Jun 24 '13 17:06

Ankit Zalani


2 Answers

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.

like image 82
rgettman Avatar answered Sep 20 '22 19:09

rgettman


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.

like image 36
MK. Avatar answered Sep 19 '22 19:09

MK.