Saeed Hassan Saeed Hassan - 6 months ago 12
Java Question

difference between (double)(1/2) and (double)1/2 in java

I want to know the difference between


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


(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.