float to int Java

float to int Java

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.

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

Examples of implicit casting float to int Java

float to int
Output screenshot of float to int Java

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.

View all for 65 types of Conversions

2 thoughts on “float to int Java

  1. gopinath

    Sir,
    Its very useful for me to learn java basics.i want to learn servletand jsp .have site like same way2java.please let me know it.

Leave a Reply

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