Reputation: 14812
Float f = new Float(10.71);
byte b = (byte)f;
I get
Cannot cast from Float to byte
Why do I have to do this?
byte b = (byte)(float)f;
Upvotes: 4
Views: 4709
Reputation: 1008
Be aware on the differences between classes and primitives.
You'll never be allowed to cast any object to a primitive. These are different entities as an object creation pass through an instantiation, hence JVM treat objects and primitives as different entities without relation between them.
The classes related to primitives (Integer, Float, ...) are used to wrap these primitives and provide some manipulation methods. Furthermore, this classes have a specific cast procedure that allows then to return the primitive they are wrapping.
Only for these objects
float myFloat = (float)f;
is equivalent to
float myFloat = f.floatValue();
Once you have your object transformed to a float type, you can cast it backwards to an int (which will remove the decimal digits obviously).
int myInt = (int)(float)f;
int mySameInt = (int)f.floatValue(); //same value than above
Upvotes: 1
Reputation: 30528
You cannot cast an Object
to a primitive. You can only cast Float
to float
because of java's autoboxing feature.
This "feature" is being assaulted endlessly by angry developers but I guess it is here to stay for backwards compatibility reasons.
I don't like it either but you have to learn to live with it. Just don't use Long
s or Float
s if you can because it is not funny when you try to do computation with null
values.
Upvotes: 11
Reputation: 5348
You cannot cast an Object to a primitive.
However, you can use the byteValue()
method from Number
class.
Upvotes: 0
Reputation: 726539
Since Float
is a "boxed" float
, you cannot cast it directly. However, in your situation you do not need casting at all - you can go directly to byte
, like this:
byte b0 = f1.byteValue();
The above is possible because Float
is a subclass of java.lang.Number
, which provides the byteValue()
method.
Upvotes: 4