核心概念

常量 作用描述
MAX_VALUE 2^31 - 1 (2147483647) int 类型能表示的最大值
MIN_VALUE -2^31 (-2147483648) int 类型能表示的最小值
SIZE 32 int 值的二进制补码位数
BYTES 4 int 值占用的字节数(Java 8+)
TYPE int.class 基本类型 int 的 Class 对象

操作步骤(详细使用示例)

1. 边界检查与验证
// 检查数值是否在 int 范围内
public boolean isIntRange(long value) {
    return value >= Integer.MIN_VALUE && value <= Integer.MAX_VALUE;
}

// 使用示例
System.out.println(isIntRange(2147483647L)); // true
System.out.println(isIntRange(2147483648L)); // false
2. 数组大小控制
// 创建最大长度的数组(实际受 JVM 内存限制)
int[] maxArray = new int[Integer.MAX_VALUE - 8]; // 减8避免OutOfMemoryError
3. 类型判断与反射
// 检查类型是否为 int
Class<?> clazz = Integer.TYPE;
System.out.println(clazz == int.class);      // true
System.out.println(clazz == Integer.class);  // false
4. 位运算与字节转换
// 将 int 拆分为字节数组
int num = 0x12345678;
byte[] bytes = new byte[Integer.BYTES];
for (int i = 0; i < Integer.BYTES; i++) {
    bytes[i] = (byte) (num >> (8 * i)); // 小端序存储
}
5. 循环边界控制
// 安全边界循环(避免溢出)
for (int i = Integer.MAX_VALUE - 10; i < Integer.MAX_VALUE; i++) {
    // 安全执行最后10次
}

常见错误与规避方法

  1. 整数溢出

    // 错误示例
    int overflow = Integer.MAX_VALUE + 1; // 实际值 = -2147483648
    
    // 正确:使用 long 或边界检查
    if (a > Integer.MAX_VALUE - b) {
        throw new ArithmeticException("Overflow!");
    }
    
  2. 混淆 SIZEBYTES

    int bits = Integer.SIZE;   // 32 (位)
    int bytes = Integer.BYTES; // 4 (字节)
    
  3. TYPE 与包装类混淆

    // 错误使用
    if (obj.getClass() == Integer.TYPE) // 永远false
    
    // 正确:判断基本类型
    if (obj instanceof Integer) { ... }
    

注意事项

  1. 常量不可变性
    所有常量均为 public static final,禁止修改:

    // Integer.MAX_VALUE = 100; // 编译错误
    
  2. BYTES 版本依赖
    BYTES 常量需 Java 8+,低版本用 Integer.SIZE / 8

  3. MIN_VALUE 绝对值不对称

    Math.abs(Integer.MIN_VALUE); // 仍为负数(-2147483648)
    

使用技巧

  1. 二进制操作优化

    // 快速计算 int 占用的字节数
    int byteSize = Integer.SIZE >>> 3; // 等价于 /8
    
  2. 安全的平均值计算

    // 避免 (a + b)/2 的溢出
    int avg = (a & b) + ((a ^ b) >> 1);
    
  3. 高效边界检查

    // 检查加法是否溢出
    boolean willOverflow = (x > 0 && y > Integer.MAX_VALUE - x);
    

最佳实践与性能优化

  1. 优先使用基本类型
    比较时避免自动拆箱:

    // 低效
    Integer a = 100;
    if (a.equals(100)) { ... }
    
    // 高效
    if (a.intValue() == 100) { ... }
    
  2. 循环边界预计算
    减少重复访问常量:

    final int max = Integer.MAX_VALUE - threshold;
    for (int i = 0; i < max; i++) { ... }
    
  3. 位运算替代乘除
    利用 SIZE 优化计算:

    // 计算 int 最大值(替代 2^31-1)
    int maxValue = (1 << 31) - 1; // 与 MAX_VALUE 相同
    

关键总结

场景 推荐常量 示例
数值边界检查 MAX_VALUE/MIN_VALUE if (value <= Integer.MAX_VALUE)
内存敏感操作 BYTES byte[] buf = new byte[n * Integer.BYTES]
类型反射 TYPE MethodType.methodType(int.class)
位运算 SIZE int mask = (1 << Integer.SIZE) - 1;

通过常量名而非字面量(如 2147483647)提升代码可读性,严格防范整数溢出风险!