Saeed Hassan - 1 year ago 33

Java Question

I want to know the difference between

`System.out.print((double)1/2);`

System.out.print((double)(1/2));

The first answer I got was 0.5, but the second one gives 0.0 .

Thanks in advance.

Answer

`(double)(1/2)`

first computes `1/2`

, which results in `0`

(int division), and then casts the result to `double`

(which gives `0.0`

).

`(double)1/2`

first casts `1`

to `double`

and then divides `1.0`

by `2`

(floating point division), resulting in `0.5`

. This is equivalent to `1.0/2`

or `1/2.0`

.

Source (Stackoverflow)