Skip to lesson

The Integer cache and == surprises

Integer a = 100, b = 100; makes a == b true, but with 1000 it is false. The reason is a small cache of shared Integer objects for values from -128 to 127, and the fact that == on two objects compares references, not values.

Integer.valueOf caches -128 to 127

The Integer cache keeps ready-made Integer objects for -128 to 127, so boxing those values returns the same object and == can seem to work by accident.

The Integer cache is a set of ready-made Integer objects for every value from -128 to 127, created when the Integer class starts up. Integer.valueOf(n) returns the cached object when n is in that range, and a new Integer object otherwise.

Example 1 · The cache boundary: 127 and 128

CacheRangeDemo.javaJava
public class CacheRangeDemo {    public static void main(String[] args) {        Integer a = 127, b = 127;           // autoboxing calls Integer.valueOf(127)        Integer c = 128, d = 128;        Integer e = -128, f = -128;        Integer g = -129, h = -129;
        System.out.println("127  == 127  : " + (a == b));        System.out.println("128  == 128  : " + (c == d));        System.out.println("-128 == -128 : " + (e == f));        System.out.println("-129 == -129 : " + (g == h));        System.out.println("128 equals 128: " + c.equals(d));    }}
Output
127  == 127  : true
128  == 128  : false
-128 == -128 : true
-129 == -129 : false
128 equals 128: true

What this code does

  • 127 and -128 are inside the cache, so both variables share one object and == is true. 128 and -129 are outside, so each autoboxing makes a new object and == is false.
  • equals compares values, so 128 equals 128 is true.

Example 2 · Autoboxing in bytecode: valueOf and intValue

Terminal
javac --release 17 BoxDemo.javajavap -c BoxDemo
Sample output
  public static void main(java.lang.String[]);
    Code:
       0: bipush        100
       2: invokestatic  #7                  // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
       5: astore_1
       6: aload_1
       7: invokevirtual #13                 // Method java/lang/Integer.intValue:()I
      10: istore_2
      11: getstatic     #17                 // Field java/lang/System.out:Ljava/io/PrintStream;
      14: iload_2
      15: invokevirtual #23                 // Method java/io/PrintStream.println:(I)V
      18: return

What this code does

  • BoxDemo.main holds three lines: Integer marks = 100; int back = marks; System.out.println(back);. This is a real javap -c listing of it, compiled by javac 21 with --release 17 (the constructor is left out). Boxing is a plain call to Integer.valueOf, the method with the cache.
  • Unboxing is intValue(). That call is what throws NullPointerException when the Integer is null.

Autoboxing uses this method. When you write Integer marks = 100;, javac turns it into Integer.valueOf(100), and unboxing (int back = marks;) becomes marks.intValue(). Small values are very common (counters, flags, loop indexes), so sharing them saves many tiny objects. The range -128 to 127 is guaranteed by the Java Language Specification. On HotSpot the upper limit can be raised with -XX:AutoBoxCacheMax=<n>, but code must never depend on that.

Why == works for 100 and fails for 1000

== on two object references asks "is this the same object?", not "do they hold the same value?". For two Integer variables it compares the references.

Left: Integer a = 100 and Integer b = 100 both point to the same cached Integer object, so a == b is true. Right: Integer c = 1000 and Integer d = 1000 point to two separate Integer objects, so c == d is false, although both hold the same number.

Example 3 · Same marks, different answers

SameMarksDemo.javaJava
import java.util.HashMap;import java.util.Map;
public class SameMarksDemo {    static void check(Map<String, Integer> marks, String x, String y) {        boolean sameRef = marks.get(x) == marks.get(y);        // compares references        boolean sameValue = marks.get(x).equals(marks.get(y));        System.out.println(x + " and " + y + ": == says " + sameRef + ", equals says " + sameValue);    }
    public static void main(String[] args) {        Map<String, Integer> unitTest = new HashMap<>();      // out of 100        unitTest.put("Asha", 85);        unitTest.put("Ravi", 85);
        Map<String, Integer> finalExam = new HashMap<>();     // out of 500        finalExam.put("Asha", 450);        finalExam.put("Ravi", 450);
        check(unitTest, "Asha", "Ravi");        check(finalExam, "Asha", "Ravi");    }}
Output
Asha and Ravi: == says true, equals says true
Asha and Ravi: == says false, equals says true

What this code does

  • Both students scored 85 in the unit test: the map holds two references to the one cached Integer for 85, so == says true.
  • In the final exam both scored 450, but each put boxed 450 into a new object. == says false while equals says true. Tests with small numbers would never catch this bug.

Example 4 · Raising the cache with -XX:AutoBoxCacheMax

Terminal
java SameMarksDemojava -XX:AutoBoxCacheMax=1000 SameMarksDemo
Sample output
Asha and Ravi: == says true, equals says true
Asha and Ravi: == says false, equals says true

Asha and Ravi: == says true, equals says true
Asha and Ravi: == says true, equals says true

What this code does

  • Real runs on OpenJDK 21. With the cache raised to 1000, 450 is cached too and the == bug disappears from the output.
  • That does not fix the code: other JVMs, other flags, or a value of 1001 bring the bug back. Fix the comparison, not the cache.

With 100, both variables got the same cached object from valueOf, so == is true. With 1000, each valueOf call made a new object, so == is false even though both hold 1000. The bug hides in tests with small numbers and appears with real data: marks out of 500, fees in rupees, roll numbers. When one side is a primitive int, Java unboxes the Integer and compares numbers, so paid == 1500 works. But if the Integer is null, that unboxing throws NullPointerException.

Predict the output

Integer: == or equals?

Read each program and pick what it prints.

Round 1 of 4

Two tickets numbered 100.

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

Caches in Byte, Short, Long, Character and Boolean

The other wrapper classes have the same kind of cache, inside their valueOf methods. Only Float and Double have none: every boxed decimal is a new object.

Example 5 · The caches of the other wrappers

OtherCachesDemo.javaJava
public class OtherCachesDemo {    public static void main(String[] args) {        Byte b1 = (byte) 100, b2 = (byte) 100;        Short s1 = (short) 127, s2 = (short) 127;        Short s3 = (short) 128, s4 = (short) 128;        Long l1 = 127L, l2 = 127L;        Long l3 = 128L, l4 = 128L;        Character c1 = 'A', c2 = 'A';               // 'A' is 65, inside 0 to 127        Character c3 = (char) 8377, c4 = (char) 8377;   // the rupee sign        Boolean t1 = true, t2 = true;        Double d1 = 1.0, d2 = 1.0;
        System.out.println("Byte 100:       " + (b1 == b2));        System.out.println("Short 127/128:  " + (s1 == s2) + " / " + (s3 == s4));        System.out.println("Long 127/128:   " + (l1 == l2) + " / " + (l3 == l4));        System.out.println("Character A/Rs: " + (c1 == c2) + " / " + (c3 == c4));        System.out.println("Boolean true:   " + (t1 == t2));        System.out.println("Double 1.0:     " + (d1 == d2));    }}
Output
Byte 100:       true
Short 127/128:  true / false
Long 127/128:   true / false
Character A/Rs: true / false
Boolean true:   true
Double 1.0:     false

What this code does

  • Short and Long share objects only from -128 to 127. Character shares 0 to 127, so 'A' (65) is cached and the rupee sign (8377) is not.
  • Boolean boxing always gives Boolean.TRUE or Boolean.FALSE. Double has no cache, so even two boxed 1.0 values are different objects.
  • Byte: every value (-128 to 127), because that is the whole range of byte.
  • Short and Long: -128 to 127, fixed.
  • Character: '\u0000' to '\u007F' (0 to 127, the ASCII characters).
  • Boolean: only two objects ever exist from boxing, Boolean.TRUE and Boolean.FALSE.
Only Integer's upper limit can be raised with a flag. The constructors such as new Integer(5) always make a new object and are deprecated for removal since Java 16: use valueOf or autoboxing.

Always compare wrappers with equals

equals compares the values inside two wrapper objects, so it works for every number, cached or not. For two values that may be null, Objects.equals(a, b) is null-safe: it returns true when both are null and never throws.

Java
Integer paid = 1500, due = 1500;paid == due                     // false: two different objectspaid.equals(due)                // true: same valueObjects.equals(paid, due)       // true, and safe when either is nullInteger.compare(paid, due)      // 0 means equal

To order wrappers use Integer.compare(a, b) or a.compareTo(b), never a == b inside a comparator. And watch the type: equals also checks the class, so Long.valueOf(1500).equals(1500) is false, because 1500 boxes to an Integer, not a Long.

Example 6 · Comparing wrappers the right way

CompareRightDemo.javaJava
import java.util.Objects;
public class CompareRightDemo {    public static void main(String[] args) {        Integer paid = 1500;        Integer due = 1500;        Integer missing = null;
        System.out.println("paid == due        : " + (paid == due));            // references: wrong        System.out.println("paid.equals(due)   : " + paid.equals(due));        System.out.println("paid == 1500       : " + (paid == 1500));        System.out.println("Objects.equals     : " + Objects.equals(missing, due)); // null-safe        System.out.println("Integer.compare    : " + Integer.compare(paid, due));   // 0 means equal
        Long upiAmount = 1500L;        System.out.println("Long equals Integer: " + upiAmount.equals(1500));        System.out.println("Long equals Long   : " + upiAmount.equals(1500L));    }}
Output
paid == due        : false
paid.equals(due)   : true
paid == 1500       : true
Objects.equals     : false
Integer.compare    : 0
Long equals Integer: false
Long equals Long   : true

What this code does

  • paid == due compares two different Integer objects. equals, Integer.compare and paid == 1500 (an int on one side, so Java unboxes) all compare the values.
  • Objects.equals(missing, due) returns false instead of throwing. upiAmount.equals(1500) is false because 1500 is boxed to an Integer and a Long only equals another Long; use 1500L.

Next step

Check your understanding

12 quick questions