Java multiply operation behavior

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).


Yes, it's pretty obvious if you've done it before. Any time you see a string of numbers multiplied out you should automatically start thinking about integer overflow errors. In this case you're set to overflow if expireTimeInDays is more than 24. Technically you should be thinking about overflow errors any time you're working with integers, but multiplying a group of them like this should be a very big red flag.


Your operand variable and the literal numbers are of type int. The int data type has a maximum value of 2^31 -1. Therefore with such large numbers, the data type of int overflows leading to a seeming incorrect answer.

In your first example, the int is only promoted to a long on assignment to the variable which occurs after the calculation. The result of the calculation is an int.

The second example, casts the first operand to a long, causing the promotion of the calculation to a long. In this case, the result of the calculation is a long, due to promotion. The long data type is more than large enough for your calculation.