1、int类型的大小范围
int最大长度是11位。在32位的机器下,int的范围是 - 2 ^ 31 ~2 ^ 31 - 1; 也就是:[-2147483648, 2147483647];在16位的机器下,int的范围为 -2 ^ 15 ~ 2 ^ 15-1。
长度超过11位
2、代码演示
public class Demo01 {
public static void main(String[] args) {
// 操作比较大的数的时候,注意溢出问题
int money = 1000000000;
int year = 20;
int year1 = 2;
int total1 = money * year;
int total11 = money * year1;
System.out.println("长度为11位:" + total1); // 长度为11位:-1474836480 计算的时候内存溢出
System.out.println("长度为10位:" + total11); // 长度为10位:2000000000内存不会溢出
long total2 = money * year;
System.out.println(total2); // 转换为long类型,观察内存是否溢出?
// 结果:-1474836480 内存还是溢出,这是因为在转换为long之前内存就溢出了,所以无效果
long total3 = money * (long)year;
System.out.println(total3); // 20000000000 结果正常 因为在计算之前就将year转换为long类型,内存不会溢出
System.out.println();
}
}

版权声明:本文为qq_45758854原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。