1
//date is a java.util date
//date.getTime() = 1485462073669
int days = 3600;
long time = date.getTime() + (days * 24 * 60 * 60 * 1000L);

This will result in time = 344094777669. If I cast the variable days, the result will be different.

date.getTime() + ((long) days * 24 * 60 * 60 * 1000L)

This will result in time = 4639062073669

Why does days need to be cast as type long for the expression to evaluate correctly?

Alex Wilson
  • 1,773
  • 1
  • 12
  • 18
  • http://stackoverflow.com/questions/1494862/multiplying-long-values – Darshan Mehta Jan 26 '17 at 20:28
  • I am more curious about why this happening. The second expression is correct, but I am wondering why I need to force the cast. According to the first link, all math is done with the largest data type so shouldn't all of the variables be cast up to long? Especially because the last number is defined as a long type. – Alex Wilson Jan 26 '17 at 20:31
  • I don't see how this code may give different results if date is the same object. Casting a int to a long should change nothing. Are you sure that the date is the same instance in both cases? A – davidxxx Jan 26 '17 at 20:31
  • Yes the date object does not change. – Alex Wilson Jan 26 '17 at 20:33
  • I tried your code, but I get the same result for both. – dsh Jan 26 '17 at 20:36
  • Yeah, there's something fishy about this. There is no overflow with the given values, so the cast to `long` shouldn't be needed. – Kayaman Jan 26 '17 at 20:37

1 Answers1

2

Java is left to right.

days *  24  *  60  *  60  *  1000L
int  * int  *  int *  int *  long
    int     *  int *  int *  long
           int     *  int *  long
                   int    *  long
                         long

You could also done the following:

1000L *  days *  24   *   60 * 60
long  *  int  *  int  *  int * int
    long      *  int  *  int * int
             long     *  int * int
                     long    * int
                           long

but... in your case it shouldn't change anything. I run your code and both approaches return the same result. Maybe the date.getTime() returned another value?

xenteros
  • 15,586
  • 12
  • 56
  • 91