double to long Java

double to long Java


After knowing primitive data types and Java rules of Data Type Casting (Type Conversion), let us cast double to long.

By memory-wise, double and long both take 8 bytes of memory. Even then, a double value cannot be assigned to a long (here, rules of casting does not work) as double carries a mantissa (value after decimal point) where as long does not (it is a whole number). In explicit casting, 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 short to byte requires explicit casting.

Examples of implicit casting

long x = 10;
double y = x;

byte x = 10;
int y = x;

Following program on double to long explains explicit casting, observe, Java style where a double is assigned to a long.


double to long
Output screenshot of double to long Java

long l1 = d1;

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

long l1 = (long) d1;

The double d1 is explicitly type casted to long l1. Observe, the syntax of explicit casting. On both sides, it should be long only. When casted, the precision of 0.5 is lost (for this reason only, compiler does not compile). 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 *