Why do these two have different meanings?
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
source to share
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.
source to share
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".
source to share