Why Does Java’s Integer.valueOf Return Cached Objects? The Hidden Mechanism Explained
An in‑depth look at a famous Java interview puzzle reveals how the compiler injects valueOf calls, how the Integer class caches values via an internal IntegerCache, and why numbers between –128 and 127 are reused, providing essential insight for developers preparing for technical interviews.
Today we explore a popular Java interview question that puzzled many developers.
The Java compiler, after compiling a .java file into a .class file, inserts a valueOf method call into variable declarations, effectively transforming the original code.
Understanding the implementation of Integer.valueOf reveals that the Integer class uses an internal static cache (IntegerCache) to avoid creating duplicate objects. The cache range defaults to -128 to 127, but can be configured via JVM options.
The cache is initialized by loading JVM configuration; if a value falls within the cached range, Integer.valueOf returns the cached instance, otherwise it creates a new Integer object.
The following image shows the relevant part of the IntegerCache class:
Running the sample code produces the result shown below, confirming the caching behavior.
In summary, the Integer cache improves performance by reusing common Integer objects, and understanding this mechanism helps answer tricky interview questions.
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.
21CTO
21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.
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.
