Checking Null Wrappers against primitive values
Asked Answered
P

5

3
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?

Prerecord answered 7/2, 2012 at 14:1 Comment(1)
What do you expect the second line to produce?Indicia
C
12

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.

Craggie answered 7/2, 2012 at 14:7 Comment(2)
Does this mentioned anywhere in JLS?Prerecord
@Muhammad, I believe it is mentioned. But I think that even better way to understand the compiler sugar is to compile code, then decompile it using one of available java decompilers (e.g jad) and see the result. You will see similar code there.Craggie
F
3

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)

Faraway answered 7/2, 2012 at 14:8 Comment(0)
M
2

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.

Mcgowan answered 7/2, 2012 at 14:8 Comment(0)
S
0

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.

Stunt answered 7/2, 2012 at 14:40 Comment(0)
C
-1

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

Coleslaw answered 23/2, 2017 at 10:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.