Why do these two have different meanings?
Double milisecondsInYear = 365*24*3600*1000;
it 1.7e9
But if I used
Double milisecondsInYear = 365*24*3600*1000.;
I got the correct answer 3.15E10
Since 365
, 24
, 3600
and 1000
- all int
literals, the calculation is performed using int
s. Overflow overflows because the true value is over Integer.MAX_VALUE
. By placing a period at the end, you turn that last literal into a literal double
. This is not a very reliable way to fix this, because the multiplication of the first three numbers is still done with int
s. The best way to handle this is to make the first number a long
or double
literal.
365L*24*3600*1000
or
365.0*24*3600*1000
Due to overflow. 365*24*3600*1000
does not fit into an int (which is a 32 bit value). If you write that in quality 365L*24*3600*1000
, then the required promotions will be performed in the correct order, and the result will be long
that can correspond to this number.
On the second line, you have an extra character, a dot at the end - this makes the number a floating point number, so you lose precision, but you can actually do multiplications.
Numbers in Java are int
s unless you specify otherwise.
When you add .
, you will have the double
computation (since 1000.0
is double
) instead int
, which is appropriate (as opposed to int
).
The former does integer math because all numbers are integers, the result is an integer (which is then expanded to double
). The result range is int
insufficient for the result. A double
or long
. So you can also use
double millisecondsInYear = (365L * 24 * 3600 * 1000);
System.out.println(millisecondsInYear);
to expand to long
. The above also outputs "3.1536E10".
The order or rating differs depending on the types you use. This is why you get different answers.