On primitive vs reference types
An int
is a primitive type, which is distinct from a reference type. Only reference types can have the value null
.
References
Related questions
On Integer
vs int
java.lang.Integer
is in fact a reference type, the designated "box" type for the primitive type int
. Thus, an Integer
variable can have the value null
.
With the introduction of autoboxing in Java, conversions from int
to Integer
and vice versa can be done implicitly. But do keep in mind that they are very different types, and in fact an attempt to unbox null
will throw NullPointerException
.
References
Related questions
On consequences of Integer
being a reference type
One consequence is already mentioned: an Integer
variable can have a null
value. Another one is that the ==
operator on two Integer
is a reference identity comparison, not numerical equality.
System.out.println(new Integer(0) == new Integer(0)); // prints "false"
Whenever possible, you should prefer primitive types to boxed types. Here's a quote from Effective Java 2nd Edition, Item 49: Prefer primitive types to boxed primitives (emphasis by author):
In summary, use primitives in preference to boxed primitive whenever you have the choice. Primitive types are simpler and faster. If you must use boxed primitives, be careful! Autoboxing reduces the verbosity, but not the danger, of using boxed primitives. When your program compares two boxed primitives with the ==
operator, it does an identity comparison, which is almost certainly not what you want. When your program does mixed-type computations involving boxed and unboxed primitives, it does unboxing, and when your program does unboxing, it can throw NullPointerException
. Finally, when your program boxes primitive values, it can result in costly and unnecessary object creations.
Related questions
When Integer
must be used
There is one glaring exception where Integer
must be used over int
: generics. Type parameters in Java generics must be reference types. So you can NOT have a List<int>
in Java; you must use a List<Integer>
instead.
Related questions
See also
On using the appropriate data structure
If you must have an int[]
that permits null
values, then the quick answer is to use Integer[]
. Since you now have an array of reference types, some elements can be null
. Be aware of all the consequences of working with reference types, or you may come across surprises.
At this point, however, I'd seriously consider using a List<Integer>
instead (see Effective Java 2nd Edition: Prefer lists to arrays). Lists are much more feature-rich than arrays, and it interoperates well with the larger Java Collections Framework.
API references