Pitfall - Unnecessary use of Primitive Wrappers can lead to NullPointerExceptions

suggest change

Sometimes, programmers who are new Java will use primitive types and wrappers interchangeably. This can lead to problems. Consider this example:

public class MyRecord {
    public int a, b;
    public Integer c, d;
}

...
MyRecord record = new MyRecord();
record.a = 1;               // OK
record.b = record.b + 1;    // OK
record.c = 1;               // OK
record.d = record.d + 1;    // throws a NullPointerException

Our MyRecord class1 relies on default initialization to initialize the values on its fields. Thus, when we new a record, the a and b fields will be set to zero, and the c and d fields will be set to null.

When we try to use the default initialized fields, we see that the int fields works all of the time, but the Integer fields work in some cases and not others. Specifically, in the case that fails (with d), what happens is that the expression on the right-hand side attempts to unbox a null reference, and that is what causes the NullPointerException to be thrown.

There are a couple of ways to look at this:

The lesson here is to not use primitive wrapper types unless you really need to.


1 - This class is not an example of good coding practice. For instance, a well-designed class would not have public fields. However, that is not the point of this example.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Pitfalls - nulls and NullPointerException:
* Pitfall - Unnecessary use of Primitive Wrappers can lead to NullPointerExceptions

Table Of Contents
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
41 Scanner
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
120 Pitfalls - nulls and NullPointerException
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap