float to char Java

float to char Java

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.

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 float requires explicit casting.

Following example on float to char Java explains explicit casting, Java style where a float is assigned to a char.

float to cha
Output screenshot of float to char Java

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.

View all for 65 types of Conversions

Leave a Reply

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