-1
class MyClass {
    public static void main(String[] args) {
        Integer a = 5;
        Integer b = 5;
        Integer c = 129;
        Integer d = 129;
        System.out.println(a == b);
        System.out.println(c == d);
    }
}

The output is

true

false

Why is this happening?

Samudra Ganguly
  • 637
  • 4
  • 24

1 Answers1

2

When using Integer wrapper objects instead of the int primitive, java globally caches these objects in this range because they are used often. This can speed up execution. Because these objects are cached, they are equal, while above the threshold a new objects is created of every integer.

When you want to compare Integers instead of ints use the .equals() method instead of ==.

Jakob F
  • 1,046
  • 10
  • 23
  • 1
    As a good rule of thumb, use `.equals()` for all *objects* (like `Integer`), and reserve the use of `==` for *primitives* (like `int`). This is because when `==` is used to compare objects it compares their references (roughly analogous to memory addresses), instead of their values. – thehale Jun 01 '21 at 16:50