Fundamentals 4 min read

Understanding Java Integer Caching and Autoboxing: Interview Questions Explained

This article explains Java's Integer autoboxing and caching mechanism through three interview code examples, detailing why comparisons of certain Integer objects yield true or false, how the IntegerCache works, and how Java's pass‑by‑value semantics affect object references.

Full-Stack Internet Architecture
Full-Stack Internet Architecture
Full-Stack Internet Architecture
Understanding Java Integer Caching and Autoboxing: Interview Questions Explained

The first interview question demonstrates that Integer a = 888; and Integer b = 888; compare false because values outside the cache range (-128 to 127) are boxed into distinct objects, while Integer c = 88; and Integer d = 88; compare true due to caching.

Java's autoboxing translates Integer a = 888; to Integer a = new Integer(888); , creating a new object each time, whereas values within the cache range are obtained via Integer.valueOf(int i) , which returns a shared instance from IntegerCache .

The relevant source code shows public static Integer valueOf(int i) { if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i); } and the static initializer that fills the cache array with Integer objects for -128 to 127.

The second question creates Integer a = new Integer(88); , passes it to test(Integer integer) , and reassigns the parameter to new Integer(99); . Because Java passes arguments by value (the reference is copied), the original a remains unchanged, so the program prints 88 .

The third question assigns a = 99; after a = new Integer(88); . The assignment autoboxes the primitive 99 using Integer.valueOf(99) , which returns the cached Integer instance for 99, effectively changing the reference of a to a new object, so the output is 99 .

Overall, the article clarifies how Java's Integer caching, autoboxing, and pass‑by‑value semantics influence object identity and output in typical interview code snippets.

JavaInterview Questionsautoboxingfundamentalsinteger caching
Full-Stack Internet Architecture
Written by

Full-Stack Internet Architecture

Introducing full-stack Internet architecture technologies centered on Java

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.