Site icon JavaGoal

Integer wrapper object interning

As you already know the == operator always checks the reference or objects. So, whenever you create an object of Integer class(Wrapper class), the valueOf() method called every time.

The value of the method checks the integer value if the value lies between -128 to 127 it returns the same reference. If value exceed from the limit then it creates a new object.
You can check the code of the ValueOf() method in JDK.

public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

Example:

public class Program
{
    public static void main(String[] args) 
    {
    	Integer a = 100;
    	Integer b = 100;
    	System.out.println(a == b);
    	a=1000;
    	b=1000;
    	System.out.println(a == b);
    }
}

Output: true
false

Exit mobile version