Why conversion of Wrapper Integer to Float is not possible in java

Why Wrapper Float typing doesn't work 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); } } 
+7
source share
5 answers

An Integer not a Float . Casting will work with objects if Integer subclass of Float , but it is not.

Java will not automatically decompress Integer into int , drop it to Float , and then automatically to Float when the only code to run this desired behavior is a cast.

Interestingly, this works:

 Float b = (float)i; 

Java will be automatically-unbox i to int , then there will be an explicit cast to Float (a extension of the primitive conversion, JLS 5.1.2 ), then the assignment conversion automatically translates it to Float .

+16
source

You ask him to do too much. You want it to unpack i, throw it in a float, and then insert it. The compiler cannot guess that unboxing I would help him. If, however, you replace (Float) cast (float) cast, it guesses what I will need to unpack to be great for float, and then happily automatically add it to Float.

+2
source

Packers must โ€œobjectifyโ€ the associated primitive types. This type of casting is done at the โ€œobject levelโ€ to express it in some way, not the actual value of the wrapped primitive type.

Since there is no relationship between Float and Integer (they are associated with Number , but they are just siblings), casting cannot be done directly.

+1
source

You can rewrite your class to work as you want:

 public class Conversion { public Float intToFloat(Integer i) { return (Float) i.floatValue(); } } 
+1
source
 public class Conversion { public static void main(String[] args) { Integer i = 234; Float b = i.floatValue(); System.out.println(b); }} 
0
source

All Articles