Why is it not allowed to assign double literal to variable of type float?

158 Views Asked by At

In java, the compiler throws an error if you try to assign a double literal to an int variable. However, it allows the assignment of an int literal to variable of type long.

    double d = 4.0;
    float f = d; // this is not allowed. 4.0 should be 4.0f

    int i = 4;
    long x = i; // this is allowed. 4 is treated same as 4L
2

There are 2 best solutions below

0
Federico klez Culloca On

Because an int fits inside a long, but if you put a double inside a float you may lose precision (it's a narrower type).

If you really must you can force this via casting

double d = 4.0;
float f = (float)d; // this is allowed
0
WJS On

Because they are of different types and widths. Since you are losing precision going from a double to a float or an long to a int you need to downcast.

double d = 4.0;
float f = (float)d;

long i = 4;
int x = (int)i;  

For the integer types, you can detect overflow by calling Math.toIntExact, and trapping for ArithmeticException.

try{
    int myInt = Math.toIntExact( myLong ) 
} catch (ArithmeticException e) {
    …
}