简体   繁体   中英

Why can not cast a double value to Byte object?

Why can't a primitive value (eg. a double) be cast to an Object (eg. a Byte)?

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

Java will not implicitly narrow a primitive value, eg from double to byte , so that you can explicitly cast it to a Byte via a boxing conversion. This guards against accidental loss of precision.

What you can do is cast the double to a byte (lowercase) explicitly; then Java will implicitly box the byte into a Byte . When you explicitly cast a primitive value to a narrower range type, then you are telling the compiler, "Yes, I'm aware that I might lose precision, but I want this conversion anyway."

Byte r = (byte) x;

You can not cast from a double to byte because the byte has a range smaller than the double and it does not contain decimals like a double does.

For example: The program does not know what to do to cast 1000.5 to a byte. A byte has a max of 128 (I believe) and it can not contain a decimal (which is the .5)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM