1000 * 60 * 60 * 24 * 30 results in a negative number [duplicate]

主宰稳场 提交于 2019-11-28 01:27:14

You are multiplying ints together, and overflow occurs because the maximum integer is 2^31 - 1. Only after the multiplications does it get converted to a long. Cast the first number as a long.

long days_30 = (long) 1000 * 60 * 60 * 24 * 30;

or use a long literal:

long days_30 = 1000L * 60 * 60 * 24 * 30;

That will force long math operations from the start.

   long days_30 = 1L * 1000 * 60 * 60 * 24 * 30;

Just change your multiplication to long days_30 = 1000L * 60 * 60 * 24 * 30;

But I'm Not A Wrapper Class

Java has limitations when it comes to primitive data types. If your long or double are too big, then it will overflow into a negative number. Try using the BigInteger class for storing larger numbers.

Check this out:

How does Java handle integer underflows and overflows and how would you check for it?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!