Java Pitfalls - Nulls and NullPointerException
suggest changeRemarks
The value null
is the default value for an uninitialized value of a field whose type is a reference type.
NullPointerException
(or NPE) is the exception that is thrown when you attempt to perform an inappropriate operation on the null
object reference. Such operations include:
- calling an instance method on a
null
target object, - accessing a field of a
null
target object, - attempting to index a
null
array object or access its length, - using a
null
object reference as the mutex in asynchronized
block, - casting a
null
object reference, - unboxing a
null
object reference, and - throwing a
null
object reference.
The most common root causes for NPEs:
- forgetting to initialize a field with a reference type,
- forgetting to initialize elements of an array of a reference type, or
- not testing the results of certain API methods that are specified as returning
null
in certain circumstances.
Examples of commonly used methods that return null
include:
- The
get(key)
method in theMap
API will return anull
if you call it with a key that doesn’t have a mapping. - The
getResource(path)
andgetResourceAsStream(path)
methods in theClassLoader
andClass
APIs will returnnull
if the resource cannot be found. - The
get()
method in theReference
API will returnnull
if the garbage collector has cleared the reference. - Various
getXxxx
methods in the Java EE servlet APIs will returnnull
if you attempt fetch a non-existent request parameter, session or session attribute and so on.
There are strategies for avoiding unwanted NPEs, such as explicitly testing for null
or using “Yoda Notation”, but these strategies often have the undesirable result of hiding problems in your code that really ought to be fixed.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents