Why can't you use a double value for a Byte object?

Why can't a primitive value (like a double) be passed to an object (like a byte)?

double x = 99;
Byte r = (Byte) x;     // Error: Cannot cast from double to Byte
System.out.println(r);

      

+3


source to share


2 answers


Java will not implicitly narrow down a primitive value e.g. from double

to byte

so that you can explicitly pass it to byte

using a boxing transform. This protects against accidental loss of accuracy.

What you can do is explicitly point double

to byte

(lowercase); then Java implicitly inserts byte

into byte

. When you explicitly apply a primitive value for a narrower range type, you are telling the compiler, "Yes, I know I might lose precision, but I want this conversion anyway."



Byte r = (byte) x;

      

+5


source


You cannot cast from binary byte because byte has a range less than double and it does not contain decimals like double.



For example: the program doesn't know what to do to transfer 1000.5 per byte. A byte has a maximum of 128 (I believe) and it cannot contain decimal (i.e. .5)

+1


source







All Articles