Java wrapper classes caching

We all know about the String pool, whereby whenever we define a string as a literal, it gets picked up from the string pool. Similarly, for wrapper classes such as Integer, Double etc., we have something called wrapper caches. For e.g., in Integer.java there is an inner class named IntegerCache.java. The purpose of IntegerCache.java is to cache integer values based on the cache size.

When we define something like :

Integer i = 10

An already created Integer instance is returned and the reference is stored in i.

But, a new instance is created if we use the keyword new. i.e., Integer i = new Integer(10), will return a new Integer instance and the reference to that instance will be stored in i.

Reference : https://howtodoinjava.com/java/basics/object-initialization-best-practices-internal-caching-in-wrapper-classes/

I’m a software engineer with a strong interest in algorithms. I love solving puzzles and love the aha moment of arriving at a solution after hours of struggle.