After knowing primitive data types and Java rules of Data Type Casting (Type Conversion), let us cast float to char.
By memory-wise, float takes 4 bytes of memory and char takes 2 bytes of memory. Assignment of 4 bytes value to 2 bytes value requires explicit casting. Moreover, float can take a negative value, but char takes only positive values.
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.
Following example on float to char Java explains explicit casting, Java style where a float is assigned to a char.
public class Conversions
public static void main(String args)
float f1 = 65.5f; // 4 bytes
// char ch = f1; // error, 4 bytes to 2 bytes
char ch = (char) f1; // type converted from float to char
System.out.println("\nfloat value: " + f1); // 65.5
System.out.println("Converted char value: " + ch); // prints A (ASCII value of 65)
float f1 = 10.5f;
We know earlier in data types, the float value must be suffixed with either F or f; else it is a compilation error.
char ch = f1;
The above statement raises a compilation error "possible loss of precision".
char ch = (char) f1;
The float f1 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.