点击上方 Java老铁,并选择 设为星标
优质文章和资料会及时送达
今天无意之间发现了一个bug,关于数值超出范围的问题。
@Test
public void test(){
long millis=System.currentTimeMillis();
long year=millis/1000/60/60/24/365;
System.out.println(year);
year=millis/(1000*60*60*24*365);
System.out.println(year);
}
按照逻辑来说,输出的year应该是同一个数,但是:
为什么回出现这样的问题呢?是因为1000*60*60*24*365已经超出了int的最大值,存在数值的溢出,所以我们改为Long类型,
1000L*60*60*24*365
运行结果为:
/**
* A constant holding the minimum value an {@code int} can
* have, -2<sup>31</sup>.
*/
@Native public static final int MIN_VALUE = 0x80000000;
/**
* A constant holding the maximum value an {@code int} can
* have, 2<sup>31</sup>-1.
*/
@Native public static final int MAX_VALUE = 0x7fffffff;
上图为int的取值范围的表示,用2的次方的形式表示:-2的31次方到2的31次方减去1。
关于Long:
/**
* A constant holding the minimum value a {@code long} can
* have, -2<sup>63</sup>.
*/
@Native public static final long MIN_VALUE = 0x8000000000000000L;
/**
* A constant holding the maximum value a {@code long} can
* have, 2<sup>63</sup>-1.
*/
@Native public static final long MAX_VALUE = 0x7fffffffffffffffL;
用2的次方的形式表示:-2的63次方到2的63次方减去1。
关注我
获取更多
Java干货
原创文章
视频资料
技术交流群