1
    Integer a = new Integer(3);
    Integer b = 3;

        System.out.println(a==b);
        System.out.println(a.equals(b));

output:
false
true

can someone explain why this example is valid?

Amin Golmahalleh
  • 3,585
  • 2
  • 23
  • 36
SP QRT
  • 95
  • 5
  • https://stackoverflow.com/questions/9030817/differences-between-new-integer123-integer-valueof123-and-just-123 – sirmagid Feb 01 '20 at 13:11
  • Does this answer your question? [How to properly compare two Integers in Java?](https://stackoverflow.com/questions/1514910/how-to-properly-compare-two-integers-in-java) – mucka Feb 01 '20 at 18:07

1 Answers1

2

The == operator compares the equality of the objects. Since both objects have their own id/location in the heap memory, this check evaluates to false.

The .equals() method compares the actual values of both objects, in this case 3, which is true.

apt-get_install_skill
  • 2,818
  • 10
  • 27