Search code examples
javaoverflowinteger-overflow

Java multiply operation behavior


I wrote a method to convert a given number from days to milliseconds:

private long expireTimeInMilliseconds;
...
public void setExpireTimeInDays(int expireTimeInDays)
{
   expireTimeInMilliseconds = expireTimeInDays * 24 * 60 * 60 * 1000;
}

I had a hard time to figure out what I did wrong. Now my question: Is that error so obvious ?

The corrected method:

private long expireTimeInMilliseconds;
...
public void setExpireTimeInDays(int expireTimeInDays)
{
   expireTimeInMilliseconds = ((long) expireTimeInDays) * 24 * 60 * 60 * 1000;
}

If I don't convert the integer to long before calculating, I get a complete wrong result.


Solution

  • Is it obvious? I guess it depends on how long you've been using Java and how many times you've had to deal with milliseconds. Of course, it should be okay for up to about 24 days...

    I think the biggest hint should be that System.currentTimeMillis() returns a long. That's a good indication that a number of milliseconds can get big. The type of the variable you're setting should be a good hint too.

    Of course, you've also got to know that if you do arithmetic operations with ints, the result will be int with wrap-around on overflow. Whether that's sufficiently obvious or not could be debated, but it would be a pretty pointless discussion. In C# if you turned overflow checking on, you'd have found the bug pretty quickly - but then not many developers do that (indeed, I don't although I probably should).