After knowing Java rules of Data Type Casting (Type Conversion), let us cast float to long. By memory-wise, float takes 4 bytes of memory and long takes 8 bytes of memory. Even then, a float value cannot be assigned to a long (here, rules of casting do not work) as float carries a mantissa (value after decimal point) where as long does not. In explicit casting, mantissa part is truncated.
See the data types order to know the brief rules of casting.
The left-side value can be assigned to any right-side value and is done implicitly. The reverse like float to long requires explicit casting.
General rules of casting does not apply here of float to long.
Examples of implicit casting
long x = 10;
float y = x;
byte x = 10; // 1 byte
int y = x; // 1 byte to 4 bytes
Following program on float to long explains explicit casting. Observe, the Java syntax of explicit casting.
public class Conversions
public static void main(String args)
float f1 = 10.5f; // 4 bytes
// long l1 = f1; // error
long l1 = (long) f1; // data truncation
System.out.println("float value: " + f1); // prints 10.5
System.out.println("Converted long value: " +l1); // prints 10
Output screenshot of float to long 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.
long l1 = f1;
The above statement raises a compilation error "possible loss of precision".
long l1 = (long) f1;
The float f1 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. Always explicit casting looses precision or data truncation.