-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
2
  • 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. Commented Mar 10, 2023 at 15:26
  • your int/long example would be equivalent to double d = f;. long x = 4L; int i = x; will not work either Commented Mar 10, 2023 at 15:26

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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) {
    …
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.