private static final double is 0

2019-07-04 09:27发布

问题:

I am trying to use the following line to specify a double constant, can anybody help explain to me why at runtime this constant has a value of 0.0:

private static final double CONSTANT = 1/2;

回答1:

1 and 2 are interpreted as integers and produce integer result of division. Add D at the end to make them interpreted as doubles.

private static final double CONSTANT = 1D/2D;


回答2:

The constant ends up with a value of 0.0 because the result of integer division is an integer, truncated. So your the value of your initialization is 0, not 0.5. To force a double result, make one or both of the operands a double:

private static final double CONSTANT = 1/2.0;  // or 1/2D, or even 1D/2D