Comparing objects with the = = operator in Java. Integer vs int


To compare objects in Java, the equals() method is used, but what if two wrapper objects for primitive types are compared:

Integer a = 120;
Integer b = 120;
Integer c = 130;
Integer d = 130;

System.out.println(a==b); // true
System.out.println(c==d); // false

Why is true returned in the first case, and false in the second?

Author: Kromster, 2018-10-16

2 answers

The Integer class contains a wrapper cache for values from -128 to 127.

If the number is in this range and the wrapper is not in the cache, a new wrapper is created and placed in the cache for later use.

If not in the range, then a new wrapper is created each time, and when comparing you will get false, since the objects are different.

For more information, see the source code of the method valueOf:

/**
 * Returns an {@code Integer} instance representing the specified
 * {@code int} value.  If a new {@code Integer} instance is not
 * required, this method should generally be used in preference to
 * the constructor {@link #Integer(int)}, as this method is likely
 * to yield significantly better space and time performance by
 * caching frequently requested values.
 *
 * This method will always cache values in the range -128 to 127,
 * inclusive, and may cache other values outside of this range.
 *
 * @param  i an {@code int} value.
 * @return an {@code Integer} instance representing {@code i}.
 * @since  1.5
 */
public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}

For comparison by value, one of the objects can be reduced to a primitive one type:

System.out.println((int)a == b)
 6
Author: Nick, 2020-10-15 14:19:00

See. javadoc class Integer, internal class IntegerCache:

/**
 * 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 {...}

That is, by default, values between -128 and 127 are cached, as specified in JLS, see 5.1.7. Boxing Conversion. If the value falls within this range, it is taken from the cache, if not, the objects will be compared.


The cache size can be controlled by changing the JVM parameters:

-XX:AutoBoxCacheMax=<cache_max_value>

Or

-Djava.lang.Integer.IntegerCache.high=<cache_max_value>
 6
Author: , 2020-10-15 16:34:18