double to byte Java

double to byte Java

After knowing primitive data types and Java rules of Data Type Casting (Type Conversion), let us cast double to byte. The byte data type takes 1 byte of memory and double takes 8 bytes of memory. Assigning 8 bytes of memory to 1 byte of memory requires explicit casting. Moreover, double takes a mantissa (value after decimal point) but byte does not (byte is whole number). In explicit casting, the mantissa part is truncated.

byte –> short –> int –> long –> float –> double

The left-side value can be assigned to any right-side value and is done implicitly. The reverse like double to byte requires explicit casting.

Examples of implicit casting

int x = 10; // 4 bytes
double y = x; // 4 bytes to 8 bytes

byte x = 10; // 1 byte
int y = x; // 1 byte to 4 bytes

Following program explains double to byte explicit casting. Observe, the Java style where a double is assigned to a byte.

double to byte
Output screenshot of double to byte Java

byte b1 = d1;

The above statement raises a compilation error" of possible loss of precision".

byte b1 = (byte) d1;

The double d1 is explicitly type casted to byte b1. Observe, the syntax of explicit casting. On both sides, it should be byte only. When casted, the precision of 0.5 is lost (for this reason only, the compiler raises error). This is known as data truncation.

View all for 65 types of Conversions

Leave a Reply

Your email address will not be published. Required fields are marked *