After knowing primitive data types and Java rules of Data Type Casting (Type Conversion), let us see the Java style of casting double to short.
The double takes 8 bytes of memory and short takes 2 bytes of memory. Assigning 8 bytes of memory to 2 bytes of memory requires explicit casting. Moreover, float takes a mantissa (float-point value) but short does not (it is a whole number). In explicit casting, mantissa part is truncated.
The left-side value can be assigned to any right-side value and is done implicitly. The reverse like float to short requires explicit casting.
Examples of implicit casting
short x = 10; // 2 bytes
double y = x; // 2 bytes to 8 bytes
byte x = 10; // 1 byte
int y = x; // 1 byte to 4 bytes
Following program on double to short explains explicit casting, Java style where a double is assigned to a short.
public class Conversions
public static void main(String args)
double d1 = 10.5; // 8 bytes
// short s1 = d1; // 8 bytes value to 2 bytes
short s1 = (short) d1; // 8 bytes double value type explicitly casted to 2 bytes short
System.out.println("\ndouble value: " + d1); // prints 10.5
System.out.println("Converted short value: " + s1); // prints 10; 0.5 gone
Output screenshot of double to short Java
short s1 = d1;
The above statement raises a compilation error "possible loss of precision".
short s1 = (short) d1;
The double d1 is explicitly type casted to short s1. Observe, the syntax of explicit casting. On both sides, it should be short only. When casted, the precision of 0.5 is lost (for this reason only, compiler does not compile). This is known as data truncation.