Multiplication operation in Java is resulting in negative value

后端 未结 4 1711
野趣味
野趣味 2020-11-29 11:15

Why does the below calculation produce a negative value?

long interval = 0;

interval = ((60000 * 60) * 24) * 30;
相关标签:
4条回答
  • 2020-11-29 12:00

    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);
    
    0 讨论(0)
  • 2020-11-29 12:00

    Because the value of the equation is causing a number so big that it wraps around It will result in a Integer. Int

    0 讨论(0)
  • 2020-11-29 12:01

    Your value is 2592000000 which is bigger than the maximum signed integer value 2^31 (2147483648). This is called integer overflow, the result overflows into negative.

    0 讨论(0)
  • 2020-11-29 12:02

    Try this, it won't be negative:

    long interval = 0;
    
    interval = ((60000L * 60L) * 24L) * 30L;
    
    0 讨论(0)
提交回复
热议问题