long to float Java

long to float Java


After knowing primitive data types and Java rules of Data Type Casting (Type Conversion), let us cast long to float as an example.

A float carries a mantissa part (value of decimal point) where as long takes a whole number. Assignment of long to float is done implicitly. Observe the following order of data types.

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

int i1 = 10; // 4 bytes
long l1 = i1; // 4 bytes to 8 bytes

byte x = 10; // 1 byte
short y = x; // 1 byte to 2 bytes

byte x = 10; // 1 byte
int y = x; // 1 byte to 4 bytes

Following program on long to float explains implicit casting, Java style a long value is assigned to a float. It is equivalent to a simple assignment.


long to float
Output screenshot of long to float Java

float f1 = l1;

As long value l1 is assigned to float f1, the whole number is converted into floating-point value 10.0.

View all for 65 types of Conversions

11 thoughts on “long to float Java

    1. S. Nageswara Rao, Corporate Trainer Post author

      I understand your doubt. Your doubt is how a 8 bytes of value of long can be assigned to 4 bytes value of float, that too implicitly? It is an exceptional case where a whole number long is assigned to floating-point number float of 4 bytes. Designers permitted this because float contains fractional part but not long.

  1. Gnandeep

    Sir,

    Float size is of 4 bytes whereas long size is of 8 bytes.

    But here long to float conversion is of implicit. Then how is it possible to store long value in float value.

    Can you explain in detail.

    Thanks in advance.

Leave a Reply

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