NullPointerExceptionis an exception that occurs when you try to use a reference to any location in memory (null), just like a reference to an object. Calling a method on a null reference or trying to access a field with a null reference will trigger aNullPointerException. These are the most common, but other methods are listed in theNullPointerExceptionjavadoc page.
The fastest example code I can think of to illustrate NullPointerException is probably:
public class Example { public static void main(String[] args) { Object obj = null; obj.hashCode(); } }
In the first line within
main, I explicitly set theObjectreferenceobjtonull. This means I have a reference, but it doesn't point to any object. Afterwards, I try to treat the reference as pointing to an object by calling its methods. This results in aNullPointerExceptionbecause there is no code to execute at the location pointed to by the reference.
(This is a technical question, but I think it's worth mentioning: a reference to null is not the same as a C pointer pointing to an invalid memory location. A null pointer doesn't actually point to anywhere, unlike pointing to exactly one Invalid positions are slightly different.)
Primitive: Variable containing data. If you want to manipulate the data in the original variable, you can manipulate the variable directly. By convention, primitive types begin with a lowercase letter. For example, variables of typeintorcharare primitives.
Reference: A variable containing the memory address of theobject, that is, a variable thatreferences theobject Code>. If you want To operate on theObjectreferenced by a reference variable, you mustdereferenceit. Dereferencing typically requires using.to access a method or field, or[to index an array. By convention, reference types are usually represented by the type starting with an uppercase letter. For example, variables of typeObjectare references.
Consider the following code, in which you declare aprimitivevariable of typeintbut do not initialize it:
int x; int y = x + x;
These two lines will crash the program because no value has been specified forxand we are trying to use the value ofxto specifyy>. All primitives must be initialized to usable values before they can be manipulated.
Now things get interesting.Referencesvariables can be set tonull, which means "I'm not referencing anything". If you explicitly set a reference variable in this way, you can get anullvalue in the reference variable, or the reference variable is not initialized and the compiler doesn't catch it (Java automatically sets the variable tonull).
If you set a reference variable to null, either explicitly or automatically via Java, and you try todereferenceit, you will get aNullPointerException.
A NullPointerException(NPE) typically occurs when you declare a variable but do not create an object and assign it to the variable before trying to use the variable's contents. So you're referencing something that doesn't actually exist.
Use the following code:
Integer num; num = new Integer(10);
The first line declares a variable named
num, but it doesn't actually contain a reference value yet. Since you haven't said what you want to point to, Java sets it tonull.
In the second line, the
newkeyword is used to instantiate (or create) an object of typeInteger, and the reference variablenumis assigned to theIntegerObject.
If you try to dereference
numbefore creating the object,, you will get aNullPointerException. In the simplest case, the compiler will catch the problem and let you know "num may not have been initialized", but sometimes you may write code that doesn't create the object directly.
For example, you might have a method like this:
public void doSomething(SomeObject obj) { // Do something to obj, assumes obj is not null obj.myMethod(); }
In this case you do not create the object
objbut assume it was created before calling thedoSomething()method. Note that the method can be called like this:
doSomething(null);
In this case,
objisnulland the statementobj.myMethod()will throwNullPointerException>.
If the method is intended to perform some operation on the object passed in like the method above, it is appropriate to throw
NullPointerExceptionbecause this is a programmer error and the programmer needs that information for debugging Purpose.
In addition toNullPointerExceptionexceptions thrown due to method logic, you can also check fornullvalues in method parameters and explicitly throw an NPE by adding something like: Followed near the beginning of the method:
// Throws an NPE with a custom error message if obj is null Objects.requireNonNull(obj, "obj must not be null");
Note that it would be helpful to explicitly statewhichobject cannot benullin the error message. The advantages of validating this are that 1) you can return your own clearer error message, 2) for the rest of the method you know that obj is not null unless it is reallocated and can be safely dereferenced.
Alternatively, in some cases, the purpose of the method is not just to operate on the object passed in, so an empty parameter may be acceptable. In this case you need to check fornull argumentsand behave differently. You should also explain this in the documentation. For example,doSomething()can be written as:
/** * @param obj An optional foo for ____. May be null, in which case * the result will be ____. */ public void doSomething(SomeObject obj) { if(obj == null) { // Do something } else { // Do something else } }
Now Java 14 adds a new language feature to show the root cause of NullPointerException. This language feature has been part of the SAP Business JVM since 2006.
In Java 14, the following is an example NullPointerException exception message:
List of situations that lead toNullPointerException
The following are all situations in which aNullPointerExceptionis directly mentioned by the Java Language Specification:
Access (i.e. get or set) theinstancefield of a null reference. (Static fields don’t count!)
Call theinstancemethod of a null reference. (Static methods do not count!)
Throws null value;
Access elements of an empty array.
Synchronize on null -synchronized (someNullReference) { ... }
Any integer/floating point operator may throwNullPointerException
if one of its operands is a boxed null reference.
If the boxed value is null, the unboxing conversion throws aNullPointerException.
Callingsuperon a null reference will throwNullPointerException. If you're confused, this is talking about qualified superclass constructor calls:
class Outer { class Inner {} } class ChildOfInner extends Outer.Inner { ChildOfInner(Outer o) { o.super(); // if o is null, NPE gets thrown } }
Usefor (element : iterable)loop to loop through an empty collection/array.
switch (foo) { ... }(whether an expression or a statement) can throwNullPointerExceptionwhenfoois empty .
name1::name2orprimaryExpression::namewill throwNullPointerExceptionname1# when evaluated in the following cases ## or primaryExpressionevaluates to null.
The comment from JLS states that
someInstance.someStaticMethod()does not throw an NPE becausesomeStaticMethodis static, butsomeInstance::someStaticMethodstill Throw NPE!
* Please note that JLS may alsoindirectlytalk a lot about NPE.
The fastest example code I can think of to illustrate NullPointerException is probably: In the first line withinNullPointerException
is an exception that occurs when you try to use a reference to any location in memory (null), just like a reference to an object. Calling a method on a null reference or trying to access a field with a null reference will trigger aNullPointerException
. These are the most common, but other methods are listed in theNullPointerExceptionjavadoc page.
main
(This is a technical question, but I think it's worth mentioning: a reference to null is not the same as a C pointer pointing to an invalid memory location. A null pointer doesn't actually point to anywhere, unlike pointing to exactly one Invalid positions are slightly different.), I explicitly set the
Objectreference
objto
null. This means I have a reference, but it doesn't point to any object. Afterwards, I try to treat the reference as pointing to an object by calling its methods. This results in a
NullPointerExceptionbecause there is no code to execute at the location pointed to by the reference.
There are two main types of variables in Java:
Primitive: Variable containing data. If you want to manipulate the data in the original variable, you can manipulate the variable directly. By convention, primitive types begin with a lowercase letter. For example, variables of type
int
orchar
are primitives.Reference: A variable containing the memory address of the
object
, that is, a variable thatreferences theobject Code>. If you want To operate on theObject
referenced by a reference variable, you mustdereferenceit. Dereferencing typically requires using.
to access a method or field, or[
to index an array. By convention, reference types are usually represented by the type starting with an uppercase letter. For example, variables of typeObject
are references.Consider the following code, in which you declare a
primitive
variable of typeintbut do not initialize it:These two lines will crash the program because no value has been specified for
x
and we are trying to use the value ofx
to specifyy
>. All primitives must be initialized to usable values before they can be manipulated.Now things get interesting.Referencesvariables can be set to
null
, which means "I'm not referencing anything". If you explicitly set a reference variable in this way, you can get anull
value in the reference variable, or the reference variable is not initialized and the compiler doesn't catch it (Java automatically sets the variable tonull
).If you set a reference variable to null, either explicitly or automatically via Java, and you try todereferenceit, you will get a
NullPointerException
.A NullPointerException
Use the following code: The first line declares a variable named(NPE) typically occurs when you declare a variable but do not create an object and assign it to the variable before trying to use the variable's contents. So you're referencing something that doesn't actually exist.
num
In the second line, the, but it doesn't actually contain a reference value yet. Since you haven't said what you want to point to, Java sets it to
null.
new
If you try to dereferencekeyword is used to instantiate (or create) an object of type
Integer, and the reference variable
numis assigned to the
IntegerObject.
num
For example, you might have a method like this: In this case you do not create the objectbefore creating the object,
, you will get aNullPointerException. In the simplest case, the compiler will catch the problem and let you know "
num may not have been initialized", but sometimes you may write code that doesn't create the object directly.
obj
In this case,but assume it was created before calling the
doSomething()method. Note that the method can be called like this:
obj
If the method is intended to perform some operation on the object passed in like the method above, it is appropriate to throwis
nulland the statement
obj.myMethod()will throw
NullPointerException>.
NullPointerException
because this is a programmer error and the programmer needs that information for debugging Purpose.
In addition to
NullPointerException
exceptions thrown due to method logic, you can also check fornull
values in method parameters and explicitly throw an NPE by adding something like: Followed near the beginning of the method:Note that it would be helpful to explicitly statewhichobject cannot be
null
in the error message. The advantages of validating this are that 1) you can return your own clearer error message, 2) for the rest of the method you know that obj is not null unless it is reallocated and can be safely dereferenced.Alternatively, in some cases, the purpose of the method is not just to operate on the object passed in, so an empty parameter may be acceptable. In this case you need to check fornull argumentsand behave differently. You should also explain this in the documentation. For example,
doSomething()
can be written as:Finally,How to use stack traces to pinpoint exceptions and causes
Sonar with the Find Error feature can detect NPE.Can sonar dynamically capture null pointer exceptions caused by JVM一个>
Now Java 14 adds a new language feature to show the root cause of NullPointerException. This language feature has been part of the SAP Business JVM since 2006.
In Java 14, the following is an example NullPointerException exception message:
List of situations that lead to
NullPointerException
The following are all situations in which a
NullPointerException
is directly mentioned by the Java Language Specification:Throws null value;
synchronized (someNullReference) { ... }
NullPointerException
NullPointerException
.super
on a null reference will throwNullPointerException
. If you're confused, this is talking about qualified superclass constructor calls:Use
for (element : iterable)
loop to loop through an empty collection/array.switch (foo) { ... }
(whether an expression or a statement) can throwNullPointerException
whenfoo
is empty .foo.new SomeInnerClass()
ThrowsNullPointerException
whenfoo
is null.
The comment from JLS states thatname1::name2
orprimaryExpression::name
will throwNullPointerException
name1# when evaluated in the following cases ## or primaryExpressionevaluates to null.
someInstance.someStaticMethod()
does not throw an NPE because
someStaticMethodis static, but
someInstance::someStaticMethodstill Throw NPE!
* Please note that JLS may alsoindirectlytalk a lot about NPE.