Java Integer 128 Trap: Why 100 == 100 Is True But 128 == 128 Is False

In Java, comparing two boxed Integer objects with == works for 100—then mysteriously returns false for 128.

1. The Counterexample

public class IntegerCacheDemo {
    public static void main(String[] args) {
        Integer x = 100, y = 100;
        Integer a = 128, b = 128;

        System.out.println("100 == 100 : " + (x == y)); // true
        System.out.println("128 == 128 : " + (a == b)); // false!
    }
}

2. Why Does This Happen?

For object types like Integer, == compares memory references, not numeric values. Java's Integer.valueOf() caches values from -128 to 127, so x and y point to the same cached object, whereas 128 allocates two separate objects.

3. The Fix: Use .equals() or Objects.equals()

import java.util.Objects;

public class IntegerEqualsFix {
    public static void main(String[] args) {
        Integer a = 128, b = 128;
        System.out.println(a.equals(b));          // true
        System.out.println(Objects.equals(a, b)); // true (and null-safe!)
    }
}

Comments

Popular posts from this blog

Java Integer Overflow: Why Adding Positive Numbers Gives a Negative Sum

C strtol Validation: Why atoi("abc") Returns 0 and How to Fix It

Why Excel Breaks Your Python CSV (1-Word UTF-8 BOM Fix)