Use if (a != null && a == b)
to test of objects should be considered equal, or if (a == null || a != b)
to test of objects should be considered unequal. Since b
is an int
rather than Integer
it can't be null. Thus, if a
is null it can't match b
.
While one could convert b
to an Integer
and then use Object.equals()
upon it, a literal interpretation of such code would ask the compiler and runtime to do a lot of needless work. While some versions of the JVM (runtime) might be able to recognize that one of the arguments to equals
will always be a non-null Integer
, and that it can thus skip a lot of the needless work and instead generate code equivalent to the if
statement above, there's no guarantee that all versions would do so (and in fact, I would be very surprised if there weren't some versions that can't).
Incidentally, this approach will test the numerical value of a
against b
even if b
happens to be numeric primitive type other than int
[e.g. short
, long
or double
]. Behavior when b
is float
might be a little unexpected [it compares b
not with the number in a
, but with the float
value nearest to a
], but when using long
or double
it will test for an exact numerical match. By contrast, approaches using equals
would report that a
was not equal to any number of any type other than int
or Integer
.