user3540466 - 11 months ago 53

Java Question

The following simple floating point arithmetic operation is not working as expected.

`double den = (1+j);`

System.out.println(den);

den = 1/den;

System.out.println(den);

double newden = 1/(1+j);

System.out.println(newden);

The above code gives the following output.

7.0

0.14285714285714285

0.0

As shown above, the first two operations work as expected but the last doesn't. I suppose that it has something to do with the variable type but still haven't figured out the problem.

Can you please explain the behaviour of arithmetic operations in Java?

Answer Source

An arithmetic operation in java is done in `int`

if there is no `float/double/long`

involved. Hence, change one of the arg to float/double and it works as expected.

The following code would work:

```
double newden = 1d/(i+j);
System.out.println(newden);
```

From the java spec:

Widening primitive conversion (ยง5.1.2) is applied to convert either or both operands as specified by the following rules, in order:

- If either operand is of type double, the other is converted to double.
- Otherwise, if either operand is of type float, the other is converted to float.
- Otherwise, if either operand is of type long, the other is converted to long.
- Otherwise, both operands are converted to type int.