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.
public class Conversions
  public static void main(String args[])
    long l1 = 10;           
    float f1 = l1;      

    System.out.println("long value: " + l1);                  // prints 10
    System.out.println("Converted float value: " + f1);     // prints 10.0

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

12 thoughts on “long to float Java”

  1. This makes no sense to me. I literally changed just one character (f to F).

    This fails:
    long l1 = 10;
    Float f1 = l1;

    System.out.println(“long value: ” + l1); // prints 10
    System.out.println(“Converted float value: ” + f1); // prints 10.0

    error: incompatible types: long cannot be converted to Float
    Float f1 = l1;

    I know this is old, but maybe someone else stumbles on this and is scratching his or her head like I am. This is still true in java 8. The original (using float instead of Float) is fine. Don’t try new Float(l1) either, that fails too.

  2. Upto now we don’t get exact answer from you
    By passing 8 bytes value into 4 bytes value .we may get loss of data.But java allows it implicitly how?

    1. 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.

  3. 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 Comment

Your email address will not be published.