Why is Wrapper Integer to Float conversion not possible in java
Asked Answered
K

5

8

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

    }
}
Kao answered 24/6, 2013 at 17:59 Comment(0)
I
17

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.

Intense answered 24/6, 2013 at 18:0 Comment(3)
This produces a NullPointerException if i is null. The solution is not safe.Attenuation
@RédaHousniAlaoui While null-checking in general is a good idea, in this question i is not null.Intense
I get your point but I think the code provided by the OP is only an experiment. I don't think he knows the value of i in production context. Anyway, at least it will be a warning for those who think your solution applies everywhere :)Attenuation
B
2

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.

Bicarbonate answered 24/6, 2013 at 18:2 Comment(0)
P
1

Wrappers are there to "objectify" the related primitive types. This sort of casting is done on the "object-level" to put it in a way, and not the actual value of the wrapped primitive type.

Since there's no relation between Float and Integer per se (they're related to Number but they're just siblings) a cast can't be done directly.

Precritical answered 24/6, 2013 at 18:2 Comment(0)
V
0
public class Conversion {
public static void main(String[] args) {
    Integer i = 234;

    Float b = i.floatValue();

    System.out.println(b);

}}
Viewfinder answered 24/6, 2013 at 18:7 Comment(0)
M
0

You could rewrite your class to work like you want:

public class Conversion {

     public Float intToFloat(Integer i) {
          return (Float) i.floatValue();
     }

}
Marcelline answered 24/6, 2013 at 18:9 Comment(1)
This produces a NullPointerException if i is null. The solution is not safe.Attenuation

© 2022 - 2024 — McMap. All rights reserved.