Integer partial integers of type Integer are cached by the JVM because they are used frequently to avoid redundant memory fragmentation. The value ranges from -128 to 127.

Integer i1 = 1000;
Integer i2 = 1000;
System.out.println(i1 == i2);
// Enter false here, because the Integer type uses == to compare the memory addresses of i1 and i2

Integer i1 = 127;
Integer i2 = 127;
System.out.println(i1 == i2);
I1 and i2 have different addresses, so the JVM will cache certain range of integers
Copy the code

We can look at the static Class IntegerCache in Integer’s Class source code, which means that values from -128-127 are used in the cache.

    /**
     * Cache to support the object identity semantics of autoboxing for values between
     * -128 and 127 (inclusive) as required by JLS.
     *
     * The cache is initialized on first usage.  The size of the cache
     * may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.
     * During VM initialization, java.lang.Integer.IntegerCache.high property
     * may be set and saved in the private system properties in the
     * sun.misc.VM class.
     */

    private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer cache[];

        static {
            // high value may be configured by property
            int h = 127;
            String integerCacheHighPropValue =
                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if(integerCacheHighPropValue ! =null) {
                try {
                    int i = parseInt(integerCacheHighPropValue);
                    i = Math.max(i, 127);
                    // Maximum array size is Integer.MAX_VALUE
                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
                } catch( NumberFormatException nfe) {
                    // If the property cannot be parsed into an int, ignore it.
                }
            }
            high = h;

            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);

            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high >= 127;
        }

        private IntegerCache(a) {}}Copy the code

Integer immutability

The source code never provides a way to modify Integer values. So every time you actually perform a numeric operation, you create a new Integer object and assign the reference address of the new object to the variable. You can break the point for debugging verification.

Integer i = 1; Integer@490 I += 1; // after the operation, the address of I is Integer@491Copy the code