Checking Null Wrappers against primitive values

女生的网名这么多〃 提交于 2019-12-06 07:58:48

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!