Integer i = null;
if (i == 3)
Why the second line above throws a NullPointerException
, IMHO, this has only one meaning which is Wrapper Object i
is to be unboxed which yields the Exception such as:
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(null);
int x = list.get(0);
EDIT: Can you supply me with some format doc?
It throws NPE because compiler does the following "magic" for you:
Integer i = null;
if (i.intValue() == 3)
Obviously i.intValue()
throws NPE when i
is null
.
Think of the wrapper class to be a holder object. Something like:
public class Integer {
private int intValue;
//getters and setters
}
If the pointer or the reference to the whole object is null
, you cant get to the value to do any boxing/unboxing
operations.
When you say:
if (i == 3)
The unboxing
occurs automatically on a null
reference, hence the exception.
When you try to compare a wrapped number with a primitive one, the wrapper is automatically un-boxed. If at that moment, the wrapper is null, you get a NullPointerException. This is one of the common pitfalls of the autoboxing system (the other being poor performance if you box/unbox numbers in a loop)
If it didn't unbox the Integer you would get strange behaviour like
Integer i1 = -129;
Integer i2 = -129;
if (i1 != i2)
System.out.println(i1 +" != " + i2);
or
Integer i1 = -129;
if (i1 != new Integer(-129))
System.out.println(i1 +" != " + -129);
This prints
-129 != -129
because the references rather than the values are different.
This can be avoided checking whether value is null before comparing it.
if (dto.getMethod() != null && dto.getMethod() == 0) // Safe check no NPE
Following page provides a nice wrapper to avoid to NPE
http://www.javawiki.org/wiki/Avoid_NullPointerException_on_Primitive_Wrapper_Objects
来源:https://stackoverflow.com/questions/9177585/checking-null-wrappers-against-primitive-values