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:
null
target object,null
target object,null
array object or access its length,null
object reference as the mutex in a synchronized
block,null
object reference,null
object reference, andnull
object reference.The most common root causes for NPEs:
null
in certain circumstances.Examples of commonly used methods that return null
include:
get(key)
method in the Map
API will return a null
if you call it with a key that doesn't have a mapping.getResource(path)
and getResourceAsStream(path)
methods in the ClassLoader
and Class
APIs will return null
if the resource cannot be found.get()
method in the Reference
API will return null
if the garbage collector has cleared the reference.getXxxx
methods in the Java EE servlet APIs will return null
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.