当某一种类型的数值达到此类型能够保存的最大(小)值之后,继续扩大(缩小),就会出现数据溢出问题。
int x = Integer.MAX_VALUE; // 得到整型的最大值
System.out.println("x = "+x);
System.out.println("x+1 = "+(x+1));
System.out.println("x+2 = "+(x+2));
输出结果:
x = 2147483647
x+1 = -2147483648
x+2 = -2147483647
当最大值加上 1 时,结果变成Integer范围中最小的值,
当最大值加上 2 时,结果变成Integer范围中第二小的值,这就发生了数据溢出。
若是想避免发生数据溢出,程序中就必须加上数值范围的检查,或者使用比Integer表示范围更大的数据类型,如Long。
为了避免 int 类型的溢出,可以在表达式中的任一常量后加上大写的 L,或是在变量前面加上 long,进行强制类型转换。
// 当程序发生数据溢出之后,可用强制类型进行转换
int x =Integer.MAX_VALUE ;
System.out.println("x = "+x);
System.out.println("x + 1 = "+(x+1));
System.out.println("x + 2 = "+(x+2L));
System.out.println("x + 3 = "+((long)x+3));
输出结果:
x = 2147483647
x + 1 = -2147483648
x + 2 = 2147483649
x + 3 = 2147483650
原文:https://www.cnblogs.com/iwasjoker/p/12908727.html