Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiplication operation in Java is resulting in negative value

Tags:

java

Why does the below calculation produce a negative value?

long interval = 0;

interval = ((60000 * 60) * 24) * 30;
like image 542
Ali Avatar asked Jun 13 '11 15:06

Ali


People also ask

What is negative multiplication?

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.

How does Java do multiplication?

In order to multiply numbers in Java, we will use the asterisk (*) between each number or variable.

Can Double have negative values Java?

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.

Are there negatives in Java?

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.


1 Answers

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);
like image 121
Jon Skeet Avatar answered Sep 21 '22 03:09

Jon Skeet