I am comparing integer object with primitive int but getting null pointer exception if Integer object is null
public static void main(String[] args) {
Integer a = null;
int b = 1;
if (a != b) {
System.out.println("True");
}
}
Output : Exception in thread "main" java.lang.NullPointerException
at com.nfdil.loyalty.common.Test.main(Test.java:10)
I am getting this because its trying to convert null integer object (a.intValue()) into primitive int
.
Is there any other way to avoid this?
您可以使用Objects.equals
:
if (!Objects.equals(a, b)) { ... }
For the sake of being able to compare the two, you can avoid this exception by casting b
to an Integer
.
Integer a = null;
int b = 0;
System.out.println(a != (Integer) b);
This will always result in true
however, since a
and (Integer) b
evaluate each evaluate to different objects.
The reason that your original code threw an exception is because the JVM tried to convert a
to an int
. a
had a value of null
however, and the JVM can't convert that to an int
. Casting the int
to an Integer
beforehand ensures that both of the compared terms are Integer
objects so they can be compared normally, without the JVM having to do any unsafe implicit casting.
If you want to compare the numerical value of the two items, you could use an approach such as this:
Integer a = null;
int b = 0;
System.out.println(!((Integer) b).equals(a));
您可以先将b
转换为Integer
,然后与.equals
进行比较:
Integer.valueOf(b).equals(a)
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
[eg 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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.