walnutmon - 10 months ago 73

Java Question

For this code block:

`int num = 5;`

int denom = 7;

double d = num / denom;

the value of

`d`

`0.0`

`double d = ((double) num) / denom;`

But is there another way to get the correct

`double`

Answer

```
double num = 5;
```

That avoids a cast. But you'll find that the cast conversions are well-defined. You don't have to guess, just check the JLS. int to double is a widening conversion. From §5.1.2:

Widening primitive conversions do not lose information about the overall magnitude of a numeric value.

[...]

Conversion of an int or a long value to float, or of a long value to double, may result in loss of precision-that is, the result may lose some of the least significant bits of the value. In this case, the resulting floating-point value will be a correctly rounded version of the integer value, using IEEE 754 round-to-nearest mode (§4.2.4).

5 can be expressed exactly as a double.

Source (Stackoverflow)