Java: Autoboxing and -XX:AutoBoxCacheMax

Autoboxing is the mechanism in Java to convert primitive type values to respective wrapper class object. Java programmer mostly use autoboxing while using collections, since collection only holds object and to put primitive type data into collection, it’s need to use wrapper classes to convert into objects.

So , here is autoboxing to assign primitive type to wrapper type directly.

  •  boolean to type Boolean
  • byte to type Byte
  • short to type Short
  • char to type Character
  • int to type Integer
  • long to type Long
  • float to type Float
  • double to type Double

You can directly compare wrapper classes using == , just like primitive types but for certain range which is by default (-128 to 127) .Which is default value of  -XX:AutoBoxCacheMax .

Here is the demo program when your object which is a autoboxed primitive type can be compared directly.

 Why caching this range :

This short range are generally used and  performance of public static valueOf( i)  as this method is likely to yield significantly better space and time performance by caching frequently requested values.

 Changing  -XX:AutoBoxCacheMax :

You can set the -XX:AutoBoxCacheMax=1000, and it will catch integer upto 1000 which means following code will results true

Note: this changing size only works for positive integer and it can’t be set less than 127.  See inner class private static class IntegerCache in

Setting Runtime VM option in Eclipse ,

Max size of -XX:AutoBoxCacheMax ;

Max cache size can’t be more than -Xmx (which is JVM heap size) . Heap size is defined by vm argument -Xmxm .
But, you as soon as JVM initialized, it allocate the memory for caching purpose. But you can’t allocate whole (-Xmx in byte)/4 (4byte is size of  int) for AutoBoxCache because of other object needed to be loaded and you might end up with java.lang.OutOfMemoryError: Java heap space.

Also, note that for other wrapper classes except Integer , have fixed caching size upto 127 only.

Leave a Reply

Your email address will not be published. Required fields are marked *