I'm trying to understand why this multiplication results in an incorrect value:
long max = (60 * 24 * 60 * 60 * 1000);
This should = 5,184,000,000
But in my Java program it = 889,032,704
Any idea why this is the case?
All of the values you're multiplying are int
s so the result is an int
which is cast to a long
after overflow has already happened. Make one of the factors a long
so that they are multiplied using 64b instructions
Try
long max = (60L * 24L * 60L * 60L * 1000L);
The L
suffix specifies that the constant is a long
value, not an int
constant.
The language specification says
An integer literal is of type
long
if it is suffixed with an ASCII letter L or l (ell); otherwise it is of typeint
(§4.2.1).
and the section on multiplication says
The type of a multiplicative expression is the promoted type of its operands.
and type promotion of two int
s leaves them as int
s:
Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:
- If either operand is of type
double
, the other is converted todouble
.- Otherwise, if either operand is of type
float
, the other is converted tofloat
.- Otherwise, if either operand is of type
long
, the other is converted tolong
.- Otherwise, both operands are converted to type
int
This is due to integer overflow. Your right-side product is represented as int
(default type of all operands) and it obliviously can't hold your "long" value.
Just make the first factor of your product long
, either as long constant 60L
, as in Mike's answer, or cast it explicitly (long) 60
:
long max = (long) 60 * 24 * 60 * 60 * 1000;
and you will get what you expect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With