public class Primitive {
public static void main(String []args) {
byte x=5;
Double y=(Double)x; //Error : Cannot cast from byte to Double.
Byte n=7;
Double m=(Double)n; //Error : cannot cast from Byte to Double.
double c=n; //working right ..."double is primitive and Byte is object ".
}
}
What is the point from preventing casting Byte to Double? .. i know Double to Byte for precision reasons if i am not wrong.
Casting double to byte Double is a higher datatype compared to byte. Therefore, double value will not be converted into byte implicitly, you need to convert it using the cast operator.
No, an object cannot be cast to a primitive value.
Casting Byte object to double Unboxed as primitive byte value. And, implicitly casted to double (widening).
There are three ways to convert a String to double value in Java, Double. parseDouble() method, Double. valueOf() method and by using new Double() constructor and then storing the resulting object into a primitive double field, autoboxing in Java will convert a Double object to the double primitive in no time.
Because that's how auto-boxing and un-boxing works.
This code works fine :
byte x = 5;
Integer i = (int) x;
Reason : boxing conversion map primitives and their wrappers directly. What I am saying is only a byte can be converted to a Byte without explicit type-casting. If you need to convert a byte
to a Double
, you need to explicitly use something like this :
byte x = 5;
Double d = (Double) (double) x;
because only a double
can be converted to a Double
.
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