JavaChallenge19

Govinda Raj
wolfie/JavaChallenge
2 min readJun 20, 2021

--

#CachedInteger

Try to solve the challenge by yourself first!

The challenge looks pretty simple here, but wait; there is a concept. In Java 5, a new feature was introduced to save the memory and improve performance for Integer type object handling. Integer objects are cached internally and reused via the same referenced objects.

  • This is applicable for Integer values in the range between –128 to +127.
  • This Integer caching works only on auto-boxing. Integer objects will not be cached when they are built using the constructor.

We have a dedicated IntegerCache class under the Integer class which is private and static in nature, which means you can not change its behavior, but you can control the size. oh, how???

Let’s go through the code.

Let’s understand it from java-docs first.

Cache to support the object identity semantics of autoboxing for values between -128 and 127 (inclusive) as required by JLS. The cache is initialized on first usage. The size of the cache may be controlled by the -XX:AutoBoxCacheMax=<size> option. During VM initialization, java.lang.Integer.IntegerCache.high property may be set and saved in the private system properties in the sun.misc.VM class.

So, firstly it checks if the user has set the value of “ -XX:AutoBoxCacheMax” at the time of the virtual machine initialization, then it picks that value as max and create an Integer (not int, the primitive one) array of size (max-low+1) and allocate memory to each element of the array. if you see, the entire code is inside the static block, and we know that static block is executed only once: the first time the class is loaded into memory. So be careful while changing the cache size else it will occupy unnecessary memory which might affect the performance. Let’s see the answer to the challenge now, you know it already.

It will print “num1 == num2”. Whenever two different object references are compared using “==,” the value is always “false.” But here, because of the Integer caching, num1 and num2 are autoboxed. Thus num1==num2 returns “true”.

If you like the challenge, let me know which java topic you want me to cover.

Thanks for reading it.

--

--

Govinda Raj
wolfie/JavaChallenge

Senior Software Developer. Tech Enthusiast and love coding. My portfolio: https://govinda-raj.github.io/