0
 private static boolean isOverDate(long targetDate, int threshold) {
    return new Date().getTime() - targetDate >= threshold * 24 * 60 * 60 * 1000;
}

I am using above function and Android Studio warns me about:

threshold * 24 * 60 * 60 * 1000: integer multiplication implicitly cast to long 

How to fix this? And why it warns?

Chaitanya Karmarkar
  • 1,425
  • 2
  • 7
  • 18

2 Answers2

3

OK, so this is a bit complicated to unpick.

On the LHS (left hand side) of the >= expression we have:

new Date().getTime() - targetDate

The type of that expression is long because targetDate is declared as long.

On the RHS we have:

threshold * 24 * 60 * 60 * 1000

That is an int because all of the operands are ints.

However that expression is likely to overflow. The value of 24 * 60 * 60 * 1000 is a "rather large", and when you multiply it by threshold, the resulting value is liable to be too big to represent as an int. If it does overflow, then the result will be truncated, and the >= test will give the wrong result.

So ... the compiler is suggesting that you should do the RHS calculation using long arithmetic. The simple way would be to declare threshold as a long. But you could also cast it to a long as in:

((long) threshold) * 24 * 60 * 60 * 1000
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
2

Since max_int is 2 147 483 648.

If your threshold is more than 25 (25 * 24 * 60 * 60 * 1000 = 2.160.000.000), it will higher than int can hold. So you will need to cast to long or the result may be incorrect.

Reference: https://stackoverflow.com/a/42671759/4316327

If an integer multiplication overflows, then the result is the low-order bits of the mathematical product as represented in some sufficiently large two's-complement format. As a result, if overflow occurs, then the sign of the result may not be the same as the sign of the mathematical product of the two operand values.

Solution:

long timeToCheck = threshold * 24 * 60 * 60 * 1000L;
return new Date().getTime() - targetDate >= timeToCheck;

or single line (different here is L after last number, it will understand that you will change type to long)

return new Date().getTime() - targetDate >= threshold * 24 * 60 * 60 * 1000L;

or casting

return new Date().getTime() - targetDate >= (long) threshold * 24 * 60 * 60 * 1000;
Harry T.
  • 3,478
  • 2
  • 21
  • 41