After knowing primitive data types and Java rules of Data Type Casting (Type Conversion), let us cast float to int.
By memory-wise, both take 4 bytes of memory. Even then, it requires explicit casting as a float carries a mantissa (value after decimal point) where as int does not. In explicit casting, mantissa part is truncated.
The left-side value can be assigned to any right-side value and is done implicitly. The reverse like float to int requires explicit casting.
Examples of implicit casting float to int Java
public class Conversions
public static void main(String args)
float f1 = 10.5f; // 4 bytes
// int i1 = f1; // 4 bytes value to 4 bytes, but here float to int
int i1 = (int) f1; // float value is explicitly type casted to int, see the Java syntgax
System.out.println("\nfloat value: " + f1); // prints 10.5
System.out.println("Converted int value: " + i1); // prints 10
We know earlier in data types, the float value must be suffixed with either F or f; else it is a compilation error.
int i1 = f1;
The above statement raises a compilation error "possible loss of precision".
int i1 = (int) f1;
The float f1 is explicitly type casted to int i1. Observe, the syntax of explicit casting. On both sides, it should be int only. When casted, the precision of 0.5 is lost (for this reason only, compiler does not compile). This is known as data truncation.