This works as expected:
byte b = 7;
var i = (int)b;
While this throws an InvalidCastException
:
byte b = 7;
object o = b;
var i = (int)o;
Why does the cast fail from an object
when the underlying type is still byte
?
Above code type casting object of a Derived class into Base class and it will throw ClassCastExcepiton if b is not an object of the Derived class. If Base and Derived class are not related to each other and doesn't part of the same type hierarchy, the cast will throw compile time error.
Type casting is a way of converting data from one data type to another data type. This process of data conversion is also known as type conversion or type coercion. In Java, we can cast both reference and primitive data types. By using casting, data can not be changed but only the data type is changed.
An example of typecasting is converting an integer to a string. This might be done in order to compare two numbers, when one number is saved as a string and the other is an integer. For example, a mail program might compare the first part of a street address with an integer.
In Java, type casting is used to convert variable values from one type to another. By casting we don't mean something to do with fishing, but it is a similar idea to casting a pot in clay. In Java when you cast you are changing the “shape” (or type) of the variable.
Because byte
has an explicit conversion to int
, but object
does not.
If you tell the compiler the object
is really a byte
, then it will once again allow you to explicitly cast to int
.
byte b = 7;
object o = b;
var i = (int)((byte)o);
References:
Casting and Type Conversions
byte
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With