Why does the below calculation produce a negative value?
long interval = 0;
interval = ((60000 * 60) * 24) * 30;
There are two simple rules to remember: When you multiply a negative number by a positive number then the product is always negative. When you multiply two negative numbers or two positive numbers then the product is always positive.
In order to multiply numbers in Java, we will use the asterisk (*) between each number or variable.
One of the tricky parts of this question is that Java has multiple data types to support numbers like byte, short, char, int, long, float, and double, out of those all are signed except char, which can not represent negative numbers.
The leftmost bit of a Java "int" variable represents the sign, the remaining 31 bits are the number itself. If the leftmost bit is zero, the number is positive, if it's a one, the number is negative.
Every expression in there is being evaluated (at compile-time, of course; it's a constant) as int * int
instead of long * long
. The result overflows at some point. So just use L
to make all the operand literals long:
interval = ((60000L * 60L) * 24L) * 30L;
Of course you could get away with only making some of the operands longs, but I tend to find it's easier to just change everything.
Having said all of this, if you're looking for "30 days-worth of milliseconds" it would be better to use:
long interval = TimeUnit.DAYS.toMillis(30);
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