对于整型变量的类型来说,每种类型都是有范围的,一旦超过了数的范围,就会发生整型溢出。
下面一段代码,就会发生整型溢出的问题。
public static void main(String[] args) {
int m = Integer.MAX_VALUE/2+1; //1073741824
int n = Integer.MAX_VALUE/2+1;
int overflow = m + n;
System.out.println(overflow); //-2147483648
}
做如下更改:
public static void main(String[] args) {
int m = Integer.MAX_VALUE/2+1; //1073741824
int n = Integer.MAX_VALUE/2+1;
long normal = (long) m + n;
System.out.println(normal); //2147483648
}