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
Post a Comment