Ankit Zalani
Ankit Zalani

Reputation: 3168

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

    }
}

Upvotes: 8

Views: 15598

Answers (5)

rgettman
rgettman

Reputation: 178263

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.

Upvotes: 17

James
James

Reputation: 427

You could rewrite your class to work like you want:

public class Conversion {

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

}

Upvotes: 0

Raghavenda Bhat
Raghavenda Bhat

Reputation: 155

public class Conversion {
public static void main(String[] args) {
    Integer i = 234;

    Float b = i.floatValue();

    System.out.println(b);

}}

Upvotes: 0

Fritz
Fritz

Reputation: 10045

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.

Upvotes: 1

MK.
MK.

Reputation: 34537

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.

Upvotes: 2

Related Questions