Why Java’s Integer Caching Can Make ‘a==b’ Return True – The Hidden Truth
Many interviewees expect the Java expression ‘a == b’ to be false and ‘c == d’ true when using Integer objects, but due to the Integer cache range and JVM settings, both comparisons can actually return true, a nuance explained through source code analysis and cache configuration.
In many Java interview questions, candidates are asked to predict the output of comparing Integer objects with the == operator. The typical expectation is that a == b (where a and b are 1000) yields false, while c == d (where c and d are 100) yields true.
public static void main(String[] args) {
Integer a = 1000, b = 1000;
Integer c = 100, d = 100;
System.out.println(a == b);
System.out.println(c == d);
}However, this expectation is not absolute. The comparison c == d is always true because the value 100 falls within Java's Integer cache range, while a == b can be either false or true depending on the JVM's cache configuration.
Java caches Integer objects via Integer.valueOf(int i). The method returns a cached instance when the value lies between IntegerCache.low and IntegerCache.high; otherwise, it creates a new Integer object.
/**
* 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.
*/
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}The cache is defined in the nested IntegerCache class:
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];
static {
int h = 127;
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
int i = Integer.parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
h = Math.min(i, Integer.MAX_VALUE - (-low) - 1);
} catch (NumberFormatException nfe) {
// ignore malformed property
}
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for (int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
assert IntegerCache.high >= 127;
}
private IntegerCache() {}
}By default, low is -128 and high is 127, so the cache covers the range [-128, 127]. Therefore, values like 100 are cached, making c == d true, while 1000 is not cached, so a == b is false.
If the JVM property java.lang.Integer.IntegerCache.high is set to a larger value, the cache range expands. In an Eclipse environment you can modify this property, after which the same code will print true for both comparisons.
After adjusting the cache size, running the program yields true and true, demonstrating that the interview answer is not universally fixed.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Interview Crash Guide
Dedicated to sharing Java interview Q&A; follow and reply "java" to receive a free premium Java interview guide.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
