3

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.

Dando18
  • 622
  • 9
  • 22

3 Answers3

7

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

Eran
  • 387,369
  • 54
  • 702
  • 768
1

The difference is the operator precedence and type promotion. In the case (double)1/2, 1 is casted to double and divided by 2 after promotion of the int 2 to double 2.0, i.e., a double division is calculated. In the case (double)(1/2) an integer division is executed and thus the result is 0, which is afterwards casted to double, i.e., 0.0.

sim
  • 1,148
  • 2
  • 9
  • 18
1

(double) (1/2), where (1/2) is evaluated to 0, because 1 and 2 are integers and the decimal is truncated. The 1/2 is evaluated first.

(double) 1/2 is the same as ((double)1)/2, which will return a double answer so the decimal will not be truncated.

Dando18
  • 622
  • 9
  • 22