-3

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
kaka
  • 597
  • 3
  • 5
  • 16
  • 3
    You've basically got `int` and `long` the wrong way round, meaning you're not doing a fair comparison. If you had `long i = 4; int x = i;` then you'd have the same issue. – Jon Skeet Mar 10 '23 at 15:26
  • your int/long example would be equivalent to `double d = f;`. `long x = 4L; int i = x;` will not work either – knittl Mar 10 '23 at 15:26

2 Answers2

4

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
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
2

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) {
    …
}
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
WJS
  • 36,363
  • 4
  • 24
  • 39