Java Integer Cache
Preethi Pattabiraman
Experienced Backend Developer | Java & Cloud Solutions Expert | Building Scalable AWS Applications | Continuous Learner & Team Collaborator
I was astounded to learn about this feature in Java called the IntegerCache.
A new functionality was added to reduce memory usage and enhance the processing of integer-type objects. Internally, integer objects are cached and utilised through the same referenced objects.
The Integer class keeps a cache of Integer instances in the range of -128 to 127, and all autoboxing, literals and uses of Integer.valueOf() will return instances from that cache for the range it covers.
When built with the constructor, integer objects will not be cached.
Below is my trial in an online IDE.
The purpose is mainly to save memory, leading to faster code due to better cache efficiency.
This is based on the assumption that these small values occur much more often than other ints and therefore it makes sense to avoid the overhead of having different objects for every instance (an Integer object takes up something like 12 bytes).
Happy learning!