Java Integer Cache - GeeksforGeeks

13 May, 2022
Pre-requisite: Inner Class of Java | Primitive Data type in Java | Autoboxing in Java
Java is not only a language but it’s a technology. Java has well-defined standards. In this article, we will discuss Integer Cache. This feature was introduced in Java 5 in order to improve memory management. Let us first have a look at a sample code to better understand this behavior. Afterward, we’ll discuss why this is implemented.
In the below-given program, you will clearly understand the logic and you will see how you have Initialized variable a and b and how Java keeps holds variable value in integer cache. After that, you will see how instances in the range of -128 to 127. This Integer Cache works only on autoboxing which means Conversion from a primitive type to an object reference is called autoboxing.
Let’s consider an example output of the java code given below:
Example:
Java
import java.io.*; class GFG {       public static void main(String[] args)    {         // Initializing variable a and b.        // Java keeps a integer cache of integer        // instances in range of -128 to 127.        // Integer Cache works only on autoboxing.        // Conversion from primitive type to object        // reference is called autoboxing.         // In range declaration (-128 to 127) then        // object reference will be same.        Integer a = 9;        Integer b = 9;         // Then it will be true because both value of        // a and b will point to the same object reference.        if (a == b)        {            System.out.println("a==b");        }        else {            System.out.println("a!=b");        }         // Not in range declaration (-128 to 127) then        // then object reference will not be same in this        // case.        Integer x = 396;        Integer y = 396;         // Then it will be false because both value of        // a and b will point to the different        // memory location.        if (x == y) {            System.out.println("x==y");        }        else        {          System.out.println("x!=y");        }    }}
Output :
a==b
x!=y
Here we expected that both should run if condition part. Because we all know that == compare reference and equals() compare data in java. But in this case, the behavior is not as expected. We had seen the output is unexpected.
Java Integer Cache Implementation:
In Java 5, a new feature was introduced to save the memory and improve performance for Integer type objects 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.
Autoboxing :  
This is equal to using the valueOf() as follows: 
Integer a=10; // this is autoboxing
Integer b==new Integer(40); // under the hood
IntegerCache Class:
IntegerCache is a private, static, and inner class of Java. As Java maintains standards and this is also nicely documented and gives complete information. Below given is the internal implementation for IntegerCache. Now, you will see the internal implementation logic for IntegerCache in java.
In the below-given program var0,var1,var2,var3, and high for the range to check the values for IntegerCache, and by checking you can also see the range values for IntegerCache such that class is for a cache of values between -128 and 127. 
It will help you when you will check any object reference values. And if the value will be in range declaration then the object reference for both values will be the same and if it is not in range declaration then the object reference will be different. So, if you will compare values even if it is same and it might be chance and you have taken out of range values then, in that case, both values even if it will same but will return false means it’s not equal because for both values object reference will be different.
Java
// A program demonstrate IntegerCache// implementation in Java. // This is how IntegerCache class works.private static class IntegerCache {      // Method and variable declaration.    static final int low = -128;    static final int high;    static final Integer[] cache;    private IntegerCache() {}     static    {        // Range value from -128 to 127        int var0 = 127;        String var1 = VM.getSavedProperty(            "java.lang.Integer.IntegerCache.high");        int var2;               // Check if var1 value is null or not.        if (var1 != null) {                      // For exception case           try {                var2 = Integer.parseInt(var1);                var2 = Math.max(var2, 127);                var0 = Math.min(var2, 2147483518);            }            catch (NumberFormatException var4) {            }        }         high = var0;               // High range for IntegerCache        cache = new Integer[high - -128 + 1];        var2 = -128;              // defining var3 values using loop.        for (int var3 = 0; var3 < cache.length; ++var3) {            cache[var3] = new Integer(var2++);        }        assert high >= 127;    }}
 Explanation of above IntegerCache Class :  
The code clearly states that the class is for a cache of values between -128 and 127. The high value of 127 can be modified by using an argument -XX: AutoBoxCacheMax=size.
Features : 
It gives you the flexibility to tune the performance according to our application use case.
It gives you a specific range for choosing numbers from –128 to 127.
Integer cache gives you the facility to cache other objects also for Example like Byte, Short, Long, etc.
 
surindertarika1234
anikaseth98
surinderdawra388
Output of Java Program
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java