After knowing primitive data types and Java rules of Data Type Casting (Type Conversion), let us cast double to char.
By memory-wise, double takes 8 bytes of memory and char take 2 bytes of memory. Assignment of 8 bytes value to 2 bytes value requires explicit casting. Moreover, double can take a negative value, but char takes only positive values (char is implicitly unsigned). In explicit casting, the mantissa part (value of after decimal point) is truncated.
The left-side value can be assigned to any right-side value and is done implicitly. The reverse like double to float requires explicit casting.
Examples of implicit casting of double to char
char x = ‘A’; // 2 bytes
double y = x; // prints 65.0 (ASCII value of A)
byte x = 10; // 1 byte
int y = x; // 1 byte to 4 bytes
Following program explains explicit casting, Java style where a double is assigned to a char.
public class DoubleToChar
public static void main(String args)
double d1 = 65.5; // 8 bytes
// char ch = d1; // 8 bytes to 2 bytes, compilation error
char ch = (char) d1; // 8 bytes double is type casted to 2 bytes char
System.out.println("double value: " + d1); // prints 65.5
System.out.println("converted to char value: " + ch); // prints A
Output screenshot of double to char Java
char ch = d1;
The above statement raises a compilation error "possible loss of precision".
char ch = (char) d1;
The double d1 is explicitly type casted to char ch. Observe, the syntax of explicit casting. On both sides, it should be char only. When casted, the precision of 0.5 is lost (for this reason only, compiler does not compile). This is known as data truncation.
In explicit casting precision is lost or data truncation may occur.