Integer Cache Autoboxing Identity

Autoboxed values from -128 to 127 are cached, so == compares the same object inside the range but distinct objects once boxing exceeds it.

JavaData Integrity

Code

snippet
public class AutoboxIdentity {

    public static void main(String[] args) {
        // -128..127 的装箱命中 IntegerCache:同一个对象
        Integer smallA = 127;
        Integer smallB = 127;
        System.out.println("127 == 127: " + (smallA == smallB));

        // 超出缓存:每次装箱都是新对象,== 比的是引用
        Integer bigA = 128;
        Integer bigB = 128;
        System.out.println("128 == 128: " + (bigA == bigB));
        System.out.println("128 equals 128: " + bigA.equals(bigB));

        // 与 int 比较触发拆箱:== 回到数值语义
        int primitive = 128;
        System.out.println("unboxed ==: " + (bigA == primitive));

        // valueOf 显式走同一缓存
        System.out.println("valueOf(127) == 127-box: " + (Integer.valueOf(127) == smallA));
    }
}

What the code does

Integer Cache Autoboxing Identity keeps everything in the class AutoboxIdentity and the function main.

Applying it

Each run prints the 5 labeled blocks 127 == 127:, 128 == 128:, 128 equals 128:, unboxed ==:, valueOf(127) == 127-box: in source order.

Statements that matter

Integer smallA = 127;
Integer smallB = 127;
int primitive = 128;

Interactive Tools for This Topic

FAQ

What does Integer Cache Autoboxing Identity print when run?
Running the file directly is enough — expect labeled output lines such as `127 == 127:`, `128 == 128:`, `128 equals 128:`.