-3

I have an if statement in my code as follows:

if (key != a[0]) /* line to be executed */

When I run my program with key = 1 (type Integer) and a[0] = 1 (type Integer), I get a true and the statement runs, i.e. 1 does not equal 1. Obviously, this is absurd.

I've done a lot of testing on this, and I can't find a value of key that will give me a false for key != a[0]. a[0] can't change, for the purposes of my program.

What's wrong?

nschmeller
  • 79
  • 1
  • 2
  • 9

1 Answers1

3

.equals() method checks for equality, == operator checks for object sameness. As long as key and a[0] are not the same Object, == will return false. .equals() on an Integer will return true.

VPK
  • 3,010
  • 1
  • 28
  • 35
Jeff Wang
  • 1,837
  • 1
  • 15
  • 29
  • Adding to the answer, `==` does not check for sameness. It checks for the object references. If both operands refer to the same object, it will return true. – VPK Jan 04 '18 at 06:12