Home » Core Java » Integer Caching in Java

Integer Caching in Java

Integer class maintains a cache of Integer instances from the values of -128 to 127(Both inclusive).
This Integer Caching is used in autoboxing, literals and Integer.valueOf().

Integer a = 10;
Integer b = 10;
System.out.println(a==b);  // output :true

It returns true as Integer class uses caching. So, whenever we use autoboxing, literals and Integer.valueOf(), It checks the integer value. If it lies in the range of -128 to 127, it will return the same object. If it is outside the range , then it will create new object. e.g.

Integer a = 1000;
Integer b = 1000;
System.out.println(a==b);  // output :false

Example of Integer caching for Integer.valueOf()

Integer x = Integer.valueOf(78);
Integer y = Integer.valueOf(78);
System.out.println(x==y); // output : true

It uses Integer caching as the value is between range -128 to 127.

Integer x = Integer.valueOf(1178);
Integer y = Integer.valueOf(1178);
System.out.println(x==y); // output : false

Output is false as the value is outside the range -128 to 127.

The whole idea behind the Integer caching is that the values from -128 to 127, are not used frequently and hence it is better to cache to improve efficiency as it prevents object creation overhead and it is faster as well.

NOTE : new operator in java always creates a new object whether the value lies between the range -128 to 127 or not.

Integer x = new Integer(11);
Integer y = new Integer(11);
System.out.println(x==y); // output : false

Here , the output is false as the new operator always creates new object.