What is a NullPointerException, and how do I fix it?
What are Null Pointer Exceptions (java.lang.NullPointerException
) and what causes them?
What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?
java nullpointerexception
locked by Robert Harvey♦ Aug 26 '14 at 23:04
This question's answers are a collaborative effort: if you see something that can be improved, just edit the answer to improve it! No additional answers can be added here
Read more about locked posts here.
comments disabled on deleted / locked posts / reviews |
What are Null Pointer Exceptions (java.lang.NullPointerException
) and what causes them?
What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?
java nullpointerexception
locked by Robert Harvey♦ Aug 26 '14 at 23:04
This question's answers are a collaborative effort: if you see something that can be improved, just edit the answer to improve it! No additional answers can be added here
Read more about locked posts here.
comments disabled on deleted / locked posts / reviews |
What are Null Pointer Exceptions (java.lang.NullPointerException
) and what causes them?
What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?
java nullpointerexception
What are Null Pointer Exceptions (java.lang.NullPointerException
) and what causes them?
What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?
java nullpointerexception
java nullpointerexception
edited May 26 '16 at 16:15
community wiki
Ziggy
locked by Robert Harvey♦ Aug 26 '14 at 23:04
This question's answers are a collaborative effort: if you see something that can be improved, just edit the answer to improve it! No additional answers can be added here
Read more about locked posts here.
locked by Robert Harvey♦ Aug 26 '14 at 23:04
This question's answers are a collaborative effort: if you see something that can be improved, just edit the answer to improve it! No additional answers can be added here
Read more about locked posts here.
comments disabled on deleted / locked posts / reviews |
comments disabled on deleted / locked posts / reviews |
12 Answers
12
active
oldest
votes
When you declare a reference variable (i.e. an object) you are really creating a pointer to an object. Consider the following code where you declare a variable of primitive type int
:
int x;
x = 10;
In this example, the variable x is an int
and Java will initialize it to 0 for you. When you assign it to 10 in the second line your value 10 is written into the memory location pointed to by x.
But, when you try to declare a reference type something different happens. Take the following code:
Integer num;
num = new Integer(10);
The first line declares a variable named num
, but, it does not contain a primitive value. Instead, it contains a pointer (because the type is Integer
which is a reference type). Since you did not say as yet what to point to Java sets it to null, meaning "I am pointing at nothing".
In the second line, the new
keyword is used to instantiate (or create) an object of type Integer and the pointer variable num
is assigned this object. You can now reference the object using the dereferencing operator .
(a dot).
The Exception
that you asked about occurs when you declare a variable but did not create an object. If you attempt to dereference num
BEFORE creating the object you get a NullPointerException
. In the most trivial cases, the compiler will catch the problem and let you know that "num may not have been initialized" but sometimes you write code that does not directly create the object.
For instance, you may have a method as follows:
public void doSomething(SomeObject obj) {
//do something to obj
}
In which case you are not creating the object obj
, rather assuming that it was created before the doSomething
method was called. Unfortunately, it is possible to call the method like this:
doSomething(null);
In which case obj
is null. If the method is intended to do something to the passed-in object, it is appropriate to throw the NullPointerException
because it's a programmer error and the programmer will need that information for debugging purposes.
Alternatively, there may be cases where the purpose of the method is not solely to operate on the passed in object, and therefore a null parameter may be acceptable. In this case, you would need to check for a null parameter and behave differently. You should also explain this in the documentation. For example, doSomething
could 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
}
}
Finally, How to pinpoint the exception & cause using Stack Trace
484
"The best way to avoid this type of exception is to always check for null when you did not create the object yourself." If the caller passes null, but null is not a valid argument for the method, then it's correct to throw the exception back at the caller because it's the caller's fault. Silently ignoring invalid input and doing nothing in the method is extremely poor advice because it hides the problem.
– Boann
Jul 29 '14 at 13:32
83
I would add a remark about this post explaining that even assignments to primitives can cause NPEs when using autoboxing:int a=b
can throw an NPE if b is anInteger
. There are cases where this is confusing to debug.
– Simon Fischer
Sep 26 '14 at 19:45
45
Is it possible to capture NPE thrown by a webapp from the web browser?like will it show in the view page source from the web browser..
– Sid
Apr 13 '15 at 14:51
62
Yes check if the object equals null before you invoke a method on it or try to access a variable it might have. Some times structuring your code can help avoid null pointer exception. eg when checking an input string with a constant string you should start with the constant string like here: if ("SomeString".equals(inputString)) {} //even if inputString is null no exception is thrown. So there are a bunch of things that you can do to try to be safe.
– Rose
Nov 11 '15 at 4:39
64
An additional way of avoidingNullPointerException
problems in your code is to use@Nullable
and@NotNull
annotations. The following answer has more information on this. Although this answer is specificially about the IntelliJ IDE, it is also applicable to other tools as is apparanet from teh comments. (BTW I am not allowed to edit this answer directly, perhaps the author can add it?)
– Arjan Mels
Jan 3 '16 at 18:17
|
show 17 more comments
NullPointerException
s are exceptions that occur when you try to use a reference that points to no location in memory (null) as though it were referencing an object. Calling a method on a null reference or trying to access a field of a null reference will trigger a NullPointerException
. These are the most common, but other ways are listed on the NullPointerException
javadoc page.
Probably the quickest example code I could come up with to illustrate a NullPointerException
would be:
public class Example {
public static void main(String args) {
Object obj = null;
obj.hashCode();
}
}
On the first line inside main
, I'm explicitly setting the Object
reference obj
equal to null
. This means I have a reference, but it isn't pointing to any object. After that, I try to treat the reference as though it points to an object by calling a method on it. This results in a NullPointerException
because there is no code to execute in the location that the reference is pointing.
(This is a technicality, but I think it bears mentioning: A reference that points to null isn't the same as a C pointer that points to an invalid memory location. A null pointer is literally not pointing anywhere, which is subtly different than pointing to a location that happens to be invalid.)
39
I understood everything you wrote there, but only because I've been coding for a while and know what a 'pointer' and a 'reference' are (and what null is, for that matter). When I try to dive right into explanations like that, my students look at me crosseyed, because there's not enough background.
– mmr
Feb 20 '09 at 4:06
26
@mmr: Thanks for the feedback, you make a valid point. It's difficult on the internet to really judge where someone is at, and at what level it's safe to start an explanation. I'll try revising this again.
– Bill the Lizard
Feb 20 '09 at 4:32
17
A more common way to get a NullPointerException in practice would be forgetting to explicitly initialize a member variable to something other thannull
before using it, like this. With local variables, the compiler would catch this error, but in this case it doesn't. Maybe that would make a useful addition to your answer?
– Ilmari Karonen
Jan 18 '14 at 9:28
22
@EJP "A null pointer is literally not pointing anywhere..."
– Bill the Lizard
Jun 13 '15 at 3:06
20
@EJP Which is exactly what that paragraph is pointing out.
– Bill the Lizard
Aug 11 '15 at 10:59
|
show 10 more comments
What is a NullPointerException?
A good place to start is the JavaDocs. They have this covered:
Thrown when an application attempts to use null in a case where an
object is required. These include:
- Calling the instance method of a null object.
- Accessing or modifying the field of a null object.
- Taking the length of null as if it were an array.
- Accessing or modifying the slots of null as if it were an array.
- Throwing null as if it were a Throwable value.
Applications should throw instances of this class to indicate other
illegal uses of the null object.
It is also the case that if you attempt to use a null reference with synchronized
, that will also throw this exception, per the JLS:
SynchronizedStatement:
synchronized ( Expression ) Block
- Otherwise, if the value of the Expression is null, a
NullPointerException
is thrown.
How do I fix it?
So you have a NullPointerException
. How do you fix it? Let's take a simple example which throws a NullPointerException
:
public class Printer {
private String name;
public void setName(String name) {
this.name = name;
}
public void print() {
printString(name);
}
private void printString(String s) {
System.out.println(s + " (" + s.length() + ")");
}
public static void main(String args) {
Printer printer = new Printer();
printer.print();
}
}
Identify the null values
The first step is identifying exactly which values are causing the exception. For this, we need to do some debugging. It's important to learn to read a stacktrace. This will show you where the exception was thrown:
Exception in thread "main" java.lang.NullPointerException
at Printer.printString(Printer.java:13)
at Printer.print(Printer.java:9)
at Printer.main(Printer.java:19)
Here, we see that the exception is thrown on line 13 (in the printString
method). Look at the line and check which values are null by
adding logging statements or using a debugger. We find out that s
is null, and calling the length
method on it throws the exception. We can see that the program stops throwing the exception when s.length()
is removed from the method.
Trace where these values come from
Next check where this value comes from. By following the callers of the method, we see that s
is passed in with printString(name)
in the print()
method, and this.name
is null.
Trace where these values should be set
Where is this.name
set? In the setName(String)
method. With some more debugging, we can see that this method isn't called at all. If the method was called, make sure to check the order that these methods are called, and the set method isn't called after the print method.
This is enough to give us a solution: add a call to printer.setName()
before calling printer.print()
.
Other fixes
The variable can have a default value (and setName
can prevent it being set to null):
private String name = "";
Either the print
or printString
method can check for null, for example:
printString((name == null) ? "" : name);
Or you can design the class so that name
always has a non-null value:
public class Printer {
private final String name;
public Printer(String name) {
this.name = Objects.requireNonNull(name);
}
public void print() {
printString(name);
}
private void printString(String s) {
System.out.println(s + " (" + s.length() + ")");
}
public static void main(String args) {
Printer printer = new Printer("123");
printer.print();
}
}
See also:
- Avoiding “!= null” statements in Java?
I still can't find the problem
If you tried to debug the problem and still don't have a solution, you can post a question for more help, but make sure to include what you've tried so far. At a minimum, include the stacktrace in the question, and mark the important line numbers in the code. Also, try simplifying the code first (see SSCCE).
39
+1 Good to have an example that includes going through the stacktrace; it's important to show why reading it is important for debugging NPE. (and why we almost always look for a stacktrace when someone posts a question about an error)
– Dennis Meng
Jun 8 '14 at 1:30
14
You mentioned debugging...How does that work? I have been researching the topic for a while now, but can find nothing. I'm sure an amazing teacher like you can teach it to me in a second! Thanks so much! :-)
– Ruchir Baronia
Dec 10 '15 at 7:07
13
@RuchirBaronia A debugger allows you to step through a program line by line to see which methods are called and how variables are changed. IDEs should have some tools to do this. See vogella.com/tutorials/EclipseDebugging/article.html for example.
– fgb
Dec 10 '15 at 10:22
13
@RuchirBaronia You set breakpoints on the methods around any NullPointerExceptions as seen in the stacktrace, and check the values of variables against what you expect them to be. If you know a variable is null when it shouldn't be, then you can set breakpoints around any code that changes the value. There are also conditional breakpoints you can use which will tell you when a value changes.
– fgb
Dec 10 '15 at 11:33
5
Setting String objects to an empty string as their default value is considered to be a poor practice.
– Tiny
Feb 27 '16 at 2:05
|
show 2 more comments
Question: What causes a NullPointerException
(NPE)?
As you should know, Java types are divided into primitive types (boolean
, int
, etc.) and reference types. Reference types in Java allow you to use the special value null
which is the Java way of saying "no object".
A NullPointerException
is thrown at runtime whenever your program attempts to use a null
as if it was a real reference. For example, if you write this:
public class Test {
public static void main(String args) {
String foo = null;
int length = foo.length(); // HERE
}
}
the statement labelled "HERE" is going to attempt to run the length()
method on a null
reference, and this will throw a NullPointerException
.
There are many ways that you could use a null
value that will result in a NullPointerException
. In fact, the only things that you can do with a null
without causing an NPE are:
- assign it to a reference variable or read it from a reference variable,
- assign it to an array element or read it from an array element (provided that array reference itself is non-null!),
- pass it as a parameter or return it as a result, or
- test it using the
==
or!=
operators, orinstanceof
.
Question: How do I read the NPE stacktrace?
Suppose that I compile and run the program above:
$ javac Test.java
$ java Test
Exception in thread "main" java.lang.NullPointerException
at Test.main(Test.java:4)
$
First observation: the compilation succeeds! The problem in the program is NOT a compilation error. It is a runtime error. (Some IDEs may warn your program will always throw an exception ... but the standard javac
compiler doesn't.)
Second observation: when I run the program, it outputs two lines of "gobbledy-gook". WRONG!! That's not gobbledy-gook. It is a stacktrace ... and it provides vital information that will help you track down the error in your code, if you take the time to read it carefully.
So let's look at what it says:
Exception in thread "main" java.lang.NullPointerException
The first line of the stack trace tells you a number of things:
- It tells you the name of the Java thread in which the exception was thrown. For a simple program with one thread (like this one), it will be "main". Let's move on ...
- It tells you the full name of the exception that was thrown; i.e.
java.lang.NullPointerException
. - If the exception has an associated error message, that will be output after the exception name.
NullPointerException
is unusual in this respect, because it rarely has an error message.
The second line is the most important one in diagnosing an NPE.
at Test.main(Test.java:4)
This tells us a number of things:
- "at Test.main" says that we were in the
main
method of theTest
class. - "Test.java:4" gives the source filename of the class, AND it tells us that the statement where this occurred is in line 4 of the file.
If you count the lines in the file above, line 4 is the one that I labeled with the "HERE" comment.
Note that in a more complicated example, there will be lots of lines in the NPE stack trace. But you can be sure that the second line (the first "at" line) will tell you where the NPE was thrown1.
In short the stack trace will tell us unambiguously which statement of the program has thrown the NPE.
1 - Not quite true. There are things called nested exceptions...
Question: How do I track down the cause of the NPE exception in my code?
This is the hard part. The short answer is to apply logical inference to the evidence provided by the stack trace, the source code and the relevant API documentation.
Let's illustrate with the simple example (above) first. We start by looking at the line that the stack trace has told us is where the NPE happened:
int length = foo.length(); // HERE
How can that throw an NPE?
In fact there is only one way: it can only happen if foo
has the value null
. We then try to run the length()
method on null
and .... BANG!
But (I hear you say) what if the NPE was thrown inside the length()
method call?
Well, if that happened, the stack trace would look different. The first "at" line would say that the exception was thrown in some line in the java.lang.String
class, and line 4 of Test.java
would be the second "at" line.
So where did that null
come from? In this case it is obvious, and it is obvious what we need to do to fix it. (Assign a non-null value to foo
.)
OK, so let's try a slightly more tricky example. This will require some logical deduction.
public class Test {
private static String foo = new String[2];
private static int test(String bar, int pos) {
return bar[pos].length();
}
public static void main(String args) {
int length = test(foo, 1);
}
}
$ javac Test.java
$ java Test
Exception in thread "main" java.lang.NullPointerException
at Test.test(Test.java:6)
at Test.main(Test.java:10)
$
So now we have two "at" lines. The first one is for this line:
return args[pos].length();
and the second one is for this line:
int length = test(foo, 1);
Looking at the first line, how could that throw an NPE? There are two ways:
- If the value of
bar
isnull
thenbar[pos]
will throw an NPE. - If the value of
bar[pos]
isnull
then callinglength()
on it will throw an NPE.
Next, we need to figure out which of those scenarios explains what is actually happening. We will start by exploring the first one:
Where does bar
come from? It is a parameter to the test
method call, and if we look at how test
was called, we can see that it comes from the foo
static variable. In addition, we can see clearly that we initialized foo
to a non-null value. That is sufficient to tentatively dismiss this explanation. (In theory, something else could change foo
to null
... but that is not happening here.)
So what about our second scenario? Well, we can see that pos
is 1
, so that means that foo[1]
must be null
. Is that possible?
Indeed it is! And that is the problem. When we initialize like this:
private static String foo = new String[2];
we allocate a String
with two elements that are initialized to null
. After that, we have not changed the contents of foo
... so foo[1]
will still be null
.
add a comment |
It's like you are trying to access an object which is null
. Consider below example:
TypeA objA;
At this time you have just declared this object but not initialized or instantiated. And whenever you try to access any property or method in it, it will throw NullPointerException
which makes sense.
See this below example as well:
String a = null;
System.out.println(a.toString()); // NullPointerException will be thrown
If we give System.out.println(a.length()); // NullPointerException will be thrown, to skip this we can handle with try catch block. thank you
– Varma
Feb 7 at 7:25
add a comment |
A null pointer exception is thrown when an application attempts to use null in a case where an object is required. These include:
- Calling the instance method of a
null
object. - Accessing or modifying the field of a
null
object. - Taking the length of
null
as if it were an array. - Accessing or modifying the slots of
null
as if it were an array. - Throwing
null
as if it were a Throwable value.
Applications should throw instances of this class to indicate other illegal uses of the null
object.
Reference: http://docs.oracle.com/javase/8/docs/api/java/lang/NullPointerException.html
11
Keep it simple, I like this answer, add this if you consider correct - Access to uninitialized attribute of an object
– Emiliano
Mar 23 '16 at 13:06
5
@Emiliano - simply accessing an initialized attribute does not cause an NPE. It is what you >>do<< with the uninitialized attribute value that causes the NPE.
– Stephen C
May 19 '16 at 6:57
8
This is from docs.oracle.com/javase/8/docs/api/java/lang/…. -1 for quoting without reference.
– Dominique Unruh
Sep 18 '16 at 17:07
1
If you want more cases: 1) using anull
as the target of asynchronized
block, 2) using anull
as the target of aswitch
, and unboxingnull
.
– Stephen C
Oct 23 '17 at 10:16
add a comment |
A NULL
pointer is one that points to nowhere. When you dereference a pointer p
, you say "give me the data at the location stored in "p". When p
is a null pointer, the location stored in p
is nowhere
, you're saying "give me the data at the location 'nowhere'". Obviously, it can't do this, so it throws a NULL pointer exception
.
In general, it's because something hasn't been initialized properly.
1
Are we creating a database ? -->NULL
is written asnull
in java. And it's a case sensitive thing.
– bvdb
Apr 25 '18 at 16:40
Lol. @bvdb Chill.
– TheRealChx101
Sep 8 '18 at 22:45
2
"A NULL pointer is one that points to nowhere" I disagree. Null pointers don't point to nowhere, they point to null values.
– TheRealChx101
Sep 8 '18 at 22:46
1
@TheRealChx101 A null pointer and a pointer to a null value are different things - a null pointer does not point to a null value. Suppose you have a pointer to a pointer: pointer A points to pointer B, and pointer B is null. In this case, pointer A points to a null value, and pointer B is a null pointer.
– MrZebra
Sep 10 '18 at 7:43
add a comment |
A lot of explanations are already present to explain how it happens and how to fix it, but you should also follow best practices to avoid NullPointerException
at all.
See also:
A good list of best practices
I would add, very important, make a good use of the final
modifier.
Using the "final" modifier whenever applicable in Java
Summary:
- Use the
final
modifier to enforce good initialization. - Avoid returning null in methods, for example returning empty collections when applicable.
- Use annotations
@NotNull
and@Nullable
- Fail fast and use asserts to avoid propagation of null objects through the whole application when they shouldn't be null.
- Use equals with a known object first:
if("knownObject".equals(unknownObject)
- Prefer
valueOf()
over toString(). - Use null safe
StringUtils
methodsStringUtils.isEmpty(null)
.
3
In j2ee projects,Nullpointer exception is very common.Some cases reference variables got null values.So You should check the variable initialization properly.And during conditional statement you should always check that flag or reference contains null or not like:- if(flag!=0) { ur code that uses flag }
– Amaresh Pattanayak
Apr 17 '15 at 12:58
12
It is worth mentioning that some IDEs (e.g. Eclipse) offer automatic nullity analisys based on customizable annotations (e.g.@Nullable
as listed above) and warn about potential errors. It is also possible to infer and generate such annotations (e.g. IntelliJ can do that) based on existing code structure.
– Jan Chimiak
Mar 5 '16 at 10:34
3
First thing should do is before using a nullable object, you should check whether is it null, usingif (obj==null)
.If it is null then you should write code to handle that also.
– Lakmal Vithanage
Feb 17 '17 at 6:52
3
IMO, it is preferable to avoid returning null objects in methods when possible and use annotation when null input parameters are not allowed in order to, by contract, reduce the amount of ´if (obj==null)´ in the code and improve the code readability.
– L. G.
Feb 27 '17 at 9:43
3
Read this ... before you accept these "best practices" as truth: satisfice.com/blog/archives/27
– Stephen C
May 21 '17 at 7:52
|
show 3 more comments
A null pointer exception is an indicator that you are using an object without initializing it.
For example, below is a student class which will use it in our code.
public class Student {
private int id;
public int getId() {
return this.id;
}
public setId(int newId) {
this.id = newId;
}
}
The below code gives you a null pointer exception.
public class School {
Student obj_Student;
public School() {
try {
obj_Student.getId();
}
catch(Exception e) {
System.out.println("Null Pointer ");
}
}
}
Because you are using Obj_Student
, but you forgot to initialize it like in the
correct code shown below:
public class School {
Student obj_Student;
public School() {
try {
obj_Student = new Student();
obj_Student.setId(12);
obj_Student.getId();
}
catch(Exception e) {
System.out.println("Null Pointer ");
}
}
}
7
While this is a nice example, may I ask what it adds to the question that isn't already covered by all the other answers?
– Mysticial
Sep 24 '13 at 6:20
13
It is simply inappropriate to use the word "uninitialized" here. The example you shown is in fact "initialized", and it is initialized with null. For uninitialized variables, compiler will complain to you.
– Adrian Shum
Sep 24 '13 at 6:32
2
An NPE may be an indicator that you are using an uninitialized field. It may be an indicator that you are doing other things. Oversimplifying to a single cause like this does not help someone solve NPE problems ... if the actual cause is not this one.
– Stephen C
May 27 '15 at 13:35
add a comment |
In Java, everything is in the form of a class.
If you want to use any object then you have two phases:
- Declare
- Initialization
Example:
- Declaration:
Object a;
- Initialization:
a=new Object();
Same for the array concept
- Declaration:
Item i=new Item[5];
- Initialization:
i[0]=new Item();
If you are not giving the initialization section then the NullpointerException
arise.
15
Declaring a primitive variable, such as an int, in Java does not create an Object.
– Michael Krause
Nov 15 '16 at 21:44
3
A NullPointerException often occurs when calling method of an instance.For example, if you declare a reference but does not make it point to any instance, NullPointerException will happen when you call its method. such as: YourClass ref = null; // or ref = anotherRef; // but anotherRef has not pointed any instance ref.someMethod(); // it will throw NullPointerException. Generally fix it in this way: Before the method is called, determine whether the reference is null. such as: if (yourRef != null) { yourRef.someMethod(); }
– sunhang
Jul 28 '17 at 10:25
2
Or use exception capture: such as: try { yourRef.someMethod(); } catch (NullPointerException e) { // TODO }
– sunhang
Jul 28 '17 at 10:25
add a comment |
In Java all the variables you declare are actually "references" to the objects (or primitives) and not the objects themselves.
When you attempt to execute one object method, the reference asks the living object to execute that method. But if the reference is referencing NULL (nothing, zero, void, nada) then there is no way the method gets executed. Then the runtime let you know this by throwing a NullPointerException.
Your reference is "pointing" to null, thus "Null -> Pointer".
The object lives in the VM memory space and the only way to access it is using this
references. Take this example:
public class Some {
private int id;
public int getId(){
return this.id;
}
public setId( int newId ) {
this.id = newId;
}
}
And on another place in your code:
Some reference = new Some(); // Point to a new object of type Some()
Some otherReference = null; // Initiallly this points to NULL
reference.setId( 1 ); // Execute setId method, now private var id is 1
System.out.println( reference.getId() ); // Prints 1 to the console
otherReference = reference // Now they both point to the only object.
reference = null; // "reference" now point to null.
// But "otherReference" still point to the "real" object so this print 1 too...
System.out.println( otherReference.getId() );
// Guess what will happen
System.out.println( reference.getId() ); // :S Throws NullPointerException because "reference" is pointing to NULL remember...
This an important thing to know - when there are no more references to an object (in the example above when reference
and otherReference
both point to null) then the object is "unreachable". There is no way we can work with it, so this object is ready to be garbage collected, and at some point, the VM will free the memory used by this object and will allocate another.
add a comment |
Another occurrence of a NullPointerException
occurs when one declares an object array, then immediately tries to dereference elements inside of it.
String phrases = new String[10];
String keyPhrase = "Bird";
for(String phrase : phrases) {
System.out.println(phrase.equals(keyPhrase));
}
This particular NPE can be avoided if the comparison order is reversed; namely, use .equals
on a guaranteed non-null object.
All elements inside of an array are initialized to their common initial value; for any type of object array, that means that all elements are null
.
You must initialize the elements in the array before accessing or dereferencing them.
String phrases = new String {"The bird", "A bird", "My bird", "Bird"};
String keyPhrase = "Bird";
for(String phrase : phrases) {
System.out.println(phrase.equals(keyPhrase));
}
operation on uninitialized object at instance level(not the class level) will lead to NullPointerException. operation need to be instance specific. if operation is at class level, saying calling a static method on uninitialized object then it will not throw NullPointerException exception. Even primitive wrapper class objects throws NullPointerException.
– Shailendra Singh
Jul 8 '16 at 15:20
1. NullPointerException is a RuntimeException, that means will appear when your program is running, you will not at compilation time.! :(, but most of the IDE help you to discover this. 2. Minimize the use of the keyword 'null' in assignment statements. :) Reference url:
– tomj0101
Dec 4 '17 at 5:49
@tomj0101 I'm thoroughly unclear as to why you made that comment... But to your second point, a pattern beforeOptional
was to return null. The keyword is fine. Knowing how to guard against it is critical. This offers one common occurrence of it and ways to mitigate it.
– Makoto
Dec 4 '17 at 5:54
NullPointerException is a run-time exception which is not recommended to catch it, but instead avoid it.
– Shomu
May 29 '18 at 10:14
@Shomu: At what point do I even suggest that it should be caught?
– Makoto
May 29 '18 at 13:25
add a comment |
12 Answers
12
active
oldest
votes
12 Answers
12
active
oldest
votes
active
oldest
votes
active
oldest
votes
When you declare a reference variable (i.e. an object) you are really creating a pointer to an object. Consider the following code where you declare a variable of primitive type int
:
int x;
x = 10;
In this example, the variable x is an int
and Java will initialize it to 0 for you. When you assign it to 10 in the second line your value 10 is written into the memory location pointed to by x.
But, when you try to declare a reference type something different happens. Take the following code:
Integer num;
num = new Integer(10);
The first line declares a variable named num
, but, it does not contain a primitive value. Instead, it contains a pointer (because the type is Integer
which is a reference type). Since you did not say as yet what to point to Java sets it to null, meaning "I am pointing at nothing".
In the second line, the new
keyword is used to instantiate (or create) an object of type Integer and the pointer variable num
is assigned this object. You can now reference the object using the dereferencing operator .
(a dot).
The Exception
that you asked about occurs when you declare a variable but did not create an object. If you attempt to dereference num
BEFORE creating the object you get a NullPointerException
. In the most trivial cases, the compiler will catch the problem and let you know that "num may not have been initialized" but sometimes you write code that does not directly create the object.
For instance, you may have a method as follows:
public void doSomething(SomeObject obj) {
//do something to obj
}
In which case you are not creating the object obj
, rather assuming that it was created before the doSomething
method was called. Unfortunately, it is possible to call the method like this:
doSomething(null);
In which case obj
is null. If the method is intended to do something to the passed-in object, it is appropriate to throw the NullPointerException
because it's a programmer error and the programmer will need that information for debugging purposes.
Alternatively, there may be cases where the purpose of the method is not solely to operate on the passed in object, and therefore a null parameter may be acceptable. In this case, you would need to check for a null parameter and behave differently. You should also explain this in the documentation. For example, doSomething
could 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
}
}
Finally, How to pinpoint the exception & cause using Stack Trace
484
"The best way to avoid this type of exception is to always check for null when you did not create the object yourself." If the caller passes null, but null is not a valid argument for the method, then it's correct to throw the exception back at the caller because it's the caller's fault. Silently ignoring invalid input and doing nothing in the method is extremely poor advice because it hides the problem.
– Boann
Jul 29 '14 at 13:32
83
I would add a remark about this post explaining that even assignments to primitives can cause NPEs when using autoboxing:int a=b
can throw an NPE if b is anInteger
. There are cases where this is confusing to debug.
– Simon Fischer
Sep 26 '14 at 19:45
45
Is it possible to capture NPE thrown by a webapp from the web browser?like will it show in the view page source from the web browser..
– Sid
Apr 13 '15 at 14:51
62
Yes check if the object equals null before you invoke a method on it or try to access a variable it might have. Some times structuring your code can help avoid null pointer exception. eg when checking an input string with a constant string you should start with the constant string like here: if ("SomeString".equals(inputString)) {} //even if inputString is null no exception is thrown. So there are a bunch of things that you can do to try to be safe.
– Rose
Nov 11 '15 at 4:39
64
An additional way of avoidingNullPointerException
problems in your code is to use@Nullable
and@NotNull
annotations. The following answer has more information on this. Although this answer is specificially about the IntelliJ IDE, it is also applicable to other tools as is apparanet from teh comments. (BTW I am not allowed to edit this answer directly, perhaps the author can add it?)
– Arjan Mels
Jan 3 '16 at 18:17
|
show 17 more comments
When you declare a reference variable (i.e. an object) you are really creating a pointer to an object. Consider the following code where you declare a variable of primitive type int
:
int x;
x = 10;
In this example, the variable x is an int
and Java will initialize it to 0 for you. When you assign it to 10 in the second line your value 10 is written into the memory location pointed to by x.
But, when you try to declare a reference type something different happens. Take the following code:
Integer num;
num = new Integer(10);
The first line declares a variable named num
, but, it does not contain a primitive value. Instead, it contains a pointer (because the type is Integer
which is a reference type). Since you did not say as yet what to point to Java sets it to null, meaning "I am pointing at nothing".
In the second line, the new
keyword is used to instantiate (or create) an object of type Integer and the pointer variable num
is assigned this object. You can now reference the object using the dereferencing operator .
(a dot).
The Exception
that you asked about occurs when you declare a variable but did not create an object. If you attempt to dereference num
BEFORE creating the object you get a NullPointerException
. In the most trivial cases, the compiler will catch the problem and let you know that "num may not have been initialized" but sometimes you write code that does not directly create the object.
For instance, you may have a method as follows:
public void doSomething(SomeObject obj) {
//do something to obj
}
In which case you are not creating the object obj
, rather assuming that it was created before the doSomething
method was called. Unfortunately, it is possible to call the method like this:
doSomething(null);
In which case obj
is null. If the method is intended to do something to the passed-in object, it is appropriate to throw the NullPointerException
because it's a programmer error and the programmer will need that information for debugging purposes.
Alternatively, there may be cases where the purpose of the method is not solely to operate on the passed in object, and therefore a null parameter may be acceptable. In this case, you would need to check for a null parameter and behave differently. You should also explain this in the documentation. For example, doSomething
could 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
}
}
Finally, How to pinpoint the exception & cause using Stack Trace
484
"The best way to avoid this type of exception is to always check for null when you did not create the object yourself." If the caller passes null, but null is not a valid argument for the method, then it's correct to throw the exception back at the caller because it's the caller's fault. Silently ignoring invalid input and doing nothing in the method is extremely poor advice because it hides the problem.
– Boann
Jul 29 '14 at 13:32
83
I would add a remark about this post explaining that even assignments to primitives can cause NPEs when using autoboxing:int a=b
can throw an NPE if b is anInteger
. There are cases where this is confusing to debug.
– Simon Fischer
Sep 26 '14 at 19:45
45
Is it possible to capture NPE thrown by a webapp from the web browser?like will it show in the view page source from the web browser..
– Sid
Apr 13 '15 at 14:51
62
Yes check if the object equals null before you invoke a method on it or try to access a variable it might have. Some times structuring your code can help avoid null pointer exception. eg when checking an input string with a constant string you should start with the constant string like here: if ("SomeString".equals(inputString)) {} //even if inputString is null no exception is thrown. So there are a bunch of things that you can do to try to be safe.
– Rose
Nov 11 '15 at 4:39
64
An additional way of avoidingNullPointerException
problems in your code is to use@Nullable
and@NotNull
annotations. The following answer has more information on this. Although this answer is specificially about the IntelliJ IDE, it is also applicable to other tools as is apparanet from teh comments. (BTW I am not allowed to edit this answer directly, perhaps the author can add it?)
– Arjan Mels
Jan 3 '16 at 18:17
|
show 17 more comments
When you declare a reference variable (i.e. an object) you are really creating a pointer to an object. Consider the following code where you declare a variable of primitive type int
:
int x;
x = 10;
In this example, the variable x is an int
and Java will initialize it to 0 for you. When you assign it to 10 in the second line your value 10 is written into the memory location pointed to by x.
But, when you try to declare a reference type something different happens. Take the following code:
Integer num;
num = new Integer(10);
The first line declares a variable named num
, but, it does not contain a primitive value. Instead, it contains a pointer (because the type is Integer
which is a reference type). Since you did not say as yet what to point to Java sets it to null, meaning "I am pointing at nothing".
In the second line, the new
keyword is used to instantiate (or create) an object of type Integer and the pointer variable num
is assigned this object. You can now reference the object using the dereferencing operator .
(a dot).
The Exception
that you asked about occurs when you declare a variable but did not create an object. If you attempt to dereference num
BEFORE creating the object you get a NullPointerException
. In the most trivial cases, the compiler will catch the problem and let you know that "num may not have been initialized" but sometimes you write code that does not directly create the object.
For instance, you may have a method as follows:
public void doSomething(SomeObject obj) {
//do something to obj
}
In which case you are not creating the object obj
, rather assuming that it was created before the doSomething
method was called. Unfortunately, it is possible to call the method like this:
doSomething(null);
In which case obj
is null. If the method is intended to do something to the passed-in object, it is appropriate to throw the NullPointerException
because it's a programmer error and the programmer will need that information for debugging purposes.
Alternatively, there may be cases where the purpose of the method is not solely to operate on the passed in object, and therefore a null parameter may be acceptable. In this case, you would need to check for a null parameter and behave differently. You should also explain this in the documentation. For example, doSomething
could 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
}
}
Finally, How to pinpoint the exception & cause using Stack Trace
When you declare a reference variable (i.e. an object) you are really creating a pointer to an object. Consider the following code where you declare a variable of primitive type int
:
int x;
x = 10;
In this example, the variable x is an int
and Java will initialize it to 0 for you. When you assign it to 10 in the second line your value 10 is written into the memory location pointed to by x.
But, when you try to declare a reference type something different happens. Take the following code:
Integer num;
num = new Integer(10);
The first line declares a variable named num
, but, it does not contain a primitive value. Instead, it contains a pointer (because the type is Integer
which is a reference type). Since you did not say as yet what to point to Java sets it to null, meaning "I am pointing at nothing".
In the second line, the new
keyword is used to instantiate (or create) an object of type Integer and the pointer variable num
is assigned this object. You can now reference the object using the dereferencing operator .
(a dot).
The Exception
that you asked about occurs when you declare a variable but did not create an object. If you attempt to dereference num
BEFORE creating the object you get a NullPointerException
. In the most trivial cases, the compiler will catch the problem and let you know that "num may not have been initialized" but sometimes you write code that does not directly create the object.
For instance, you may have a method as follows:
public void doSomething(SomeObject obj) {
//do something to obj
}
In which case you are not creating the object obj
, rather assuming that it was created before the doSomething
method was called. Unfortunately, it is possible to call the method like this:
doSomething(null);
In which case obj
is null. If the method is intended to do something to the passed-in object, it is appropriate to throw the NullPointerException
because it's a programmer error and the programmer will need that information for debugging purposes.
Alternatively, there may be cases where the purpose of the method is not solely to operate on the passed in object, and therefore a null parameter may be acceptable. In this case, you would need to check for a null parameter and behave differently. You should also explain this in the documentation. For example, doSomething
could 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
}
}
Finally, How to pinpoint the exception & cause using Stack Trace
edited May 12 '18 at 4:34
community wiki
16 revs, 14 users 63%
Vincent Ramdhanie
484
"The best way to avoid this type of exception is to always check for null when you did not create the object yourself." If the caller passes null, but null is not a valid argument for the method, then it's correct to throw the exception back at the caller because it's the caller's fault. Silently ignoring invalid input and doing nothing in the method is extremely poor advice because it hides the problem.
– Boann
Jul 29 '14 at 13:32
83
I would add a remark about this post explaining that even assignments to primitives can cause NPEs when using autoboxing:int a=b
can throw an NPE if b is anInteger
. There are cases where this is confusing to debug.
– Simon Fischer
Sep 26 '14 at 19:45
45
Is it possible to capture NPE thrown by a webapp from the web browser?like will it show in the view page source from the web browser..
– Sid
Apr 13 '15 at 14:51
62
Yes check if the object equals null before you invoke a method on it or try to access a variable it might have. Some times structuring your code can help avoid null pointer exception. eg when checking an input string with a constant string you should start with the constant string like here: if ("SomeString".equals(inputString)) {} //even if inputString is null no exception is thrown. So there are a bunch of things that you can do to try to be safe.
– Rose
Nov 11 '15 at 4:39
64
An additional way of avoidingNullPointerException
problems in your code is to use@Nullable
and@NotNull
annotations. The following answer has more information on this. Although this answer is specificially about the IntelliJ IDE, it is also applicable to other tools as is apparanet from teh comments. (BTW I am not allowed to edit this answer directly, perhaps the author can add it?)
– Arjan Mels
Jan 3 '16 at 18:17
|
show 17 more comments
484
"The best way to avoid this type of exception is to always check for null when you did not create the object yourself." If the caller passes null, but null is not a valid argument for the method, then it's correct to throw the exception back at the caller because it's the caller's fault. Silently ignoring invalid input and doing nothing in the method is extremely poor advice because it hides the problem.
– Boann
Jul 29 '14 at 13:32
83
I would add a remark about this post explaining that even assignments to primitives can cause NPEs when using autoboxing:int a=b
can throw an NPE if b is anInteger
. There are cases where this is confusing to debug.
– Simon Fischer
Sep 26 '14 at 19:45
45
Is it possible to capture NPE thrown by a webapp from the web browser?like will it show in the view page source from the web browser..
– Sid
Apr 13 '15 at 14:51
62
Yes check if the object equals null before you invoke a method on it or try to access a variable it might have. Some times structuring your code can help avoid null pointer exception. eg when checking an input string with a constant string you should start with the constant string like here: if ("SomeString".equals(inputString)) {} //even if inputString is null no exception is thrown. So there are a bunch of things that you can do to try to be safe.
– Rose
Nov 11 '15 at 4:39
64
An additional way of avoidingNullPointerException
problems in your code is to use@Nullable
and@NotNull
annotations. The following answer has more information on this. Although this answer is specificially about the IntelliJ IDE, it is also applicable to other tools as is apparanet from teh comments. (BTW I am not allowed to edit this answer directly, perhaps the author can add it?)
– Arjan Mels
Jan 3 '16 at 18:17
484
484
"The best way to avoid this type of exception is to always check for null when you did not create the object yourself." If the caller passes null, but null is not a valid argument for the method, then it's correct to throw the exception back at the caller because it's the caller's fault. Silently ignoring invalid input and doing nothing in the method is extremely poor advice because it hides the problem.
– Boann
Jul 29 '14 at 13:32
"The best way to avoid this type of exception is to always check for null when you did not create the object yourself." If the caller passes null, but null is not a valid argument for the method, then it's correct to throw the exception back at the caller because it's the caller's fault. Silently ignoring invalid input and doing nothing in the method is extremely poor advice because it hides the problem.
– Boann
Jul 29 '14 at 13:32
83
83
I would add a remark about this post explaining that even assignments to primitives can cause NPEs when using autoboxing:
int a=b
can throw an NPE if b is an Integer
. There are cases where this is confusing to debug.– Simon Fischer
Sep 26 '14 at 19:45
I would add a remark about this post explaining that even assignments to primitives can cause NPEs when using autoboxing:
int a=b
can throw an NPE if b is an Integer
. There are cases where this is confusing to debug.– Simon Fischer
Sep 26 '14 at 19:45
45
45
Is it possible to capture NPE thrown by a webapp from the web browser?like will it show in the view page source from the web browser..
– Sid
Apr 13 '15 at 14:51
Is it possible to capture NPE thrown by a webapp from the web browser?like will it show in the view page source from the web browser..
– Sid
Apr 13 '15 at 14:51
62
62
Yes check if the object equals null before you invoke a method on it or try to access a variable it might have. Some times structuring your code can help avoid null pointer exception. eg when checking an input string with a constant string you should start with the constant string like here: if ("SomeString".equals(inputString)) {} //even if inputString is null no exception is thrown. So there are a bunch of things that you can do to try to be safe.
– Rose
Nov 11 '15 at 4:39
Yes check if the object equals null before you invoke a method on it or try to access a variable it might have. Some times structuring your code can help avoid null pointer exception. eg when checking an input string with a constant string you should start with the constant string like here: if ("SomeString".equals(inputString)) {} //even if inputString is null no exception is thrown. So there are a bunch of things that you can do to try to be safe.
– Rose
Nov 11 '15 at 4:39
64
64
An additional way of avoiding
NullPointerException
problems in your code is to use @Nullable
and @NotNull
annotations. The following answer has more information on this. Although this answer is specificially about the IntelliJ IDE, it is also applicable to other tools as is apparanet from teh comments. (BTW I am not allowed to edit this answer directly, perhaps the author can add it?)– Arjan Mels
Jan 3 '16 at 18:17
An additional way of avoiding
NullPointerException
problems in your code is to use @Nullable
and @NotNull
annotations. The following answer has more information on this. Although this answer is specificially about the IntelliJ IDE, it is also applicable to other tools as is apparanet from teh comments. (BTW I am not allowed to edit this answer directly, perhaps the author can add it?)– Arjan Mels
Jan 3 '16 at 18:17
|
show 17 more comments
NullPointerException
s are exceptions that occur when you try to use a reference that points to no location in memory (null) as though it were referencing an object. Calling a method on a null reference or trying to access a field of a null reference will trigger a NullPointerException
. These are the most common, but other ways are listed on the NullPointerException
javadoc page.
Probably the quickest example code I could come up with to illustrate a NullPointerException
would be:
public class Example {
public static void main(String args) {
Object obj = null;
obj.hashCode();
}
}
On the first line inside main
, I'm explicitly setting the Object
reference obj
equal to null
. This means I have a reference, but it isn't pointing to any object. After that, I try to treat the reference as though it points to an object by calling a method on it. This results in a NullPointerException
because there is no code to execute in the location that the reference is pointing.
(This is a technicality, but I think it bears mentioning: A reference that points to null isn't the same as a C pointer that points to an invalid memory location. A null pointer is literally not pointing anywhere, which is subtly different than pointing to a location that happens to be invalid.)
39
I understood everything you wrote there, but only because I've been coding for a while and know what a 'pointer' and a 'reference' are (and what null is, for that matter). When I try to dive right into explanations like that, my students look at me crosseyed, because there's not enough background.
– mmr
Feb 20 '09 at 4:06
26
@mmr: Thanks for the feedback, you make a valid point. It's difficult on the internet to really judge where someone is at, and at what level it's safe to start an explanation. I'll try revising this again.
– Bill the Lizard
Feb 20 '09 at 4:32
17
A more common way to get a NullPointerException in practice would be forgetting to explicitly initialize a member variable to something other thannull
before using it, like this. With local variables, the compiler would catch this error, but in this case it doesn't. Maybe that would make a useful addition to your answer?
– Ilmari Karonen
Jan 18 '14 at 9:28
22
@EJP "A null pointer is literally not pointing anywhere..."
– Bill the Lizard
Jun 13 '15 at 3:06
20
@EJP Which is exactly what that paragraph is pointing out.
– Bill the Lizard
Aug 11 '15 at 10:59
|
show 10 more comments
NullPointerException
s are exceptions that occur when you try to use a reference that points to no location in memory (null) as though it were referencing an object. Calling a method on a null reference or trying to access a field of a null reference will trigger a NullPointerException
. These are the most common, but other ways are listed on the NullPointerException
javadoc page.
Probably the quickest example code I could come up with to illustrate a NullPointerException
would be:
public class Example {
public static void main(String args) {
Object obj = null;
obj.hashCode();
}
}
On the first line inside main
, I'm explicitly setting the Object
reference obj
equal to null
. This means I have a reference, but it isn't pointing to any object. After that, I try to treat the reference as though it points to an object by calling a method on it. This results in a NullPointerException
because there is no code to execute in the location that the reference is pointing.
(This is a technicality, but I think it bears mentioning: A reference that points to null isn't the same as a C pointer that points to an invalid memory location. A null pointer is literally not pointing anywhere, which is subtly different than pointing to a location that happens to be invalid.)
39
I understood everything you wrote there, but only because I've been coding for a while and know what a 'pointer' and a 'reference' are (and what null is, for that matter). When I try to dive right into explanations like that, my students look at me crosseyed, because there's not enough background.
– mmr
Feb 20 '09 at 4:06
26
@mmr: Thanks for the feedback, you make a valid point. It's difficult on the internet to really judge where someone is at, and at what level it's safe to start an explanation. I'll try revising this again.
– Bill the Lizard
Feb 20 '09 at 4:32
17
A more common way to get a NullPointerException in practice would be forgetting to explicitly initialize a member variable to something other thannull
before using it, like this. With local variables, the compiler would catch this error, but in this case it doesn't. Maybe that would make a useful addition to your answer?
– Ilmari Karonen
Jan 18 '14 at 9:28
22
@EJP "A null pointer is literally not pointing anywhere..."
– Bill the Lizard
Jun 13 '15 at 3:06
20
@EJP Which is exactly what that paragraph is pointing out.
– Bill the Lizard
Aug 11 '15 at 10:59
|
show 10 more comments
NullPointerException
s are exceptions that occur when you try to use a reference that points to no location in memory (null) as though it were referencing an object. Calling a method on a null reference or trying to access a field of a null reference will trigger a NullPointerException
. These are the most common, but other ways are listed on the NullPointerException
javadoc page.
Probably the quickest example code I could come up with to illustrate a NullPointerException
would be:
public class Example {
public static void main(String args) {
Object obj = null;
obj.hashCode();
}
}
On the first line inside main
, I'm explicitly setting the Object
reference obj
equal to null
. This means I have a reference, but it isn't pointing to any object. After that, I try to treat the reference as though it points to an object by calling a method on it. This results in a NullPointerException
because there is no code to execute in the location that the reference is pointing.
(This is a technicality, but I think it bears mentioning: A reference that points to null isn't the same as a C pointer that points to an invalid memory location. A null pointer is literally not pointing anywhere, which is subtly different than pointing to a location that happens to be invalid.)
NullPointerException
s are exceptions that occur when you try to use a reference that points to no location in memory (null) as though it were referencing an object. Calling a method on a null reference or trying to access a field of a null reference will trigger a NullPointerException
. These are the most common, but other ways are listed on the NullPointerException
javadoc page.
Probably the quickest example code I could come up with to illustrate a NullPointerException
would be:
public class Example {
public static void main(String args) {
Object obj = null;
obj.hashCode();
}
}
On the first line inside main
, I'm explicitly setting the Object
reference obj
equal to null
. This means I have a reference, but it isn't pointing to any object. After that, I try to treat the reference as though it points to an object by calling a method on it. This results in a NullPointerException
because there is no code to execute in the location that the reference is pointing.
(This is a technicality, but I think it bears mentioning: A reference that points to null isn't the same as a C pointer that points to an invalid memory location. A null pointer is literally not pointing anywhere, which is subtly different than pointing to a location that happens to be invalid.)
edited Dec 25 '17 at 14:24
community wiki
8 revs, 5 users 74%
Bill the Lizard
39
I understood everything you wrote there, but only because I've been coding for a while and know what a 'pointer' and a 'reference' are (and what null is, for that matter). When I try to dive right into explanations like that, my students look at me crosseyed, because there's not enough background.
– mmr
Feb 20 '09 at 4:06
26
@mmr: Thanks for the feedback, you make a valid point. It's difficult on the internet to really judge where someone is at, and at what level it's safe to start an explanation. I'll try revising this again.
– Bill the Lizard
Feb 20 '09 at 4:32
17
A more common way to get a NullPointerException in practice would be forgetting to explicitly initialize a member variable to something other thannull
before using it, like this. With local variables, the compiler would catch this error, but in this case it doesn't. Maybe that would make a useful addition to your answer?
– Ilmari Karonen
Jan 18 '14 at 9:28
22
@EJP "A null pointer is literally not pointing anywhere..."
– Bill the Lizard
Jun 13 '15 at 3:06
20
@EJP Which is exactly what that paragraph is pointing out.
– Bill the Lizard
Aug 11 '15 at 10:59
|
show 10 more comments
39
I understood everything you wrote there, but only because I've been coding for a while and know what a 'pointer' and a 'reference' are (and what null is, for that matter). When I try to dive right into explanations like that, my students look at me crosseyed, because there's not enough background.
– mmr
Feb 20 '09 at 4:06
26
@mmr: Thanks for the feedback, you make a valid point. It's difficult on the internet to really judge where someone is at, and at what level it's safe to start an explanation. I'll try revising this again.
– Bill the Lizard
Feb 20 '09 at 4:32
17
A more common way to get a NullPointerException in practice would be forgetting to explicitly initialize a member variable to something other thannull
before using it, like this. With local variables, the compiler would catch this error, but in this case it doesn't. Maybe that would make a useful addition to your answer?
– Ilmari Karonen
Jan 18 '14 at 9:28
22
@EJP "A null pointer is literally not pointing anywhere..."
– Bill the Lizard
Jun 13 '15 at 3:06
20
@EJP Which is exactly what that paragraph is pointing out.
– Bill the Lizard
Aug 11 '15 at 10:59
39
39
I understood everything you wrote there, but only because I've been coding for a while and know what a 'pointer' and a 'reference' are (and what null is, for that matter). When I try to dive right into explanations like that, my students look at me crosseyed, because there's not enough background.
– mmr
Feb 20 '09 at 4:06
I understood everything you wrote there, but only because I've been coding for a while and know what a 'pointer' and a 'reference' are (and what null is, for that matter). When I try to dive right into explanations like that, my students look at me crosseyed, because there's not enough background.
– mmr
Feb 20 '09 at 4:06
26
26
@mmr: Thanks for the feedback, you make a valid point. It's difficult on the internet to really judge where someone is at, and at what level it's safe to start an explanation. I'll try revising this again.
– Bill the Lizard
Feb 20 '09 at 4:32
@mmr: Thanks for the feedback, you make a valid point. It's difficult on the internet to really judge where someone is at, and at what level it's safe to start an explanation. I'll try revising this again.
– Bill the Lizard
Feb 20 '09 at 4:32
17
17
A more common way to get a NullPointerException in practice would be forgetting to explicitly initialize a member variable to something other than
null
before using it, like this. With local variables, the compiler would catch this error, but in this case it doesn't. Maybe that would make a useful addition to your answer?– Ilmari Karonen
Jan 18 '14 at 9:28
A more common way to get a NullPointerException in practice would be forgetting to explicitly initialize a member variable to something other than
null
before using it, like this. With local variables, the compiler would catch this error, but in this case it doesn't. Maybe that would make a useful addition to your answer?– Ilmari Karonen
Jan 18 '14 at 9:28
22
22
@EJP "A null pointer is literally not pointing anywhere..."
– Bill the Lizard
Jun 13 '15 at 3:06
@EJP "A null pointer is literally not pointing anywhere..."
– Bill the Lizard
Jun 13 '15 at 3:06
20
20
@EJP Which is exactly what that paragraph is pointing out.
– Bill the Lizard
Aug 11 '15 at 10:59
@EJP Which is exactly what that paragraph is pointing out.
– Bill the Lizard
Aug 11 '15 at 10:59
|
show 10 more comments
What is a NullPointerException?
A good place to start is the JavaDocs. They have this covered:
Thrown when an application attempts to use null in a case where an
object is required. These include:
- Calling the instance method of a null object.
- Accessing or modifying the field of a null object.
- Taking the length of null as if it were an array.
- Accessing or modifying the slots of null as if it were an array.
- Throwing null as if it were a Throwable value.
Applications should throw instances of this class to indicate other
illegal uses of the null object.
It is also the case that if you attempt to use a null reference with synchronized
, that will also throw this exception, per the JLS:
SynchronizedStatement:
synchronized ( Expression ) Block
- Otherwise, if the value of the Expression is null, a
NullPointerException
is thrown.
How do I fix it?
So you have a NullPointerException
. How do you fix it? Let's take a simple example which throws a NullPointerException
:
public class Printer {
private String name;
public void setName(String name) {
this.name = name;
}
public void print() {
printString(name);
}
private void printString(String s) {
System.out.println(s + " (" + s.length() + ")");
}
public static void main(String args) {
Printer printer = new Printer();
printer.print();
}
}
Identify the null values
The first step is identifying exactly which values are causing the exception. For this, we need to do some debugging. It's important to learn to read a stacktrace. This will show you where the exception was thrown:
Exception in thread "main" java.lang.NullPointerException
at Printer.printString(Printer.java:13)
at Printer.print(Printer.java:9)
at Printer.main(Printer.java:19)
Here, we see that the exception is thrown on line 13 (in the printString
method). Look at the line and check which values are null by
adding logging statements or using a debugger. We find out that s
is null, and calling the length
method on it throws the exception. We can see that the program stops throwing the exception when s.length()
is removed from the method.
Trace where these values come from
Next check where this value comes from. By following the callers of the method, we see that s
is passed in with printString(name)
in the print()
method, and this.name
is null.
Trace where these values should be set
Where is this.name
set? In the setName(String)
method. With some more debugging, we can see that this method isn't called at all. If the method was called, make sure to check the order that these methods are called, and the set method isn't called after the print method.
This is enough to give us a solution: add a call to printer.setName()
before calling printer.print()
.
Other fixes
The variable can have a default value (and setName
can prevent it being set to null):
private String name = "";
Either the print
or printString
method can check for null, for example:
printString((name == null) ? "" : name);
Or you can design the class so that name
always has a non-null value:
public class Printer {
private final String name;
public Printer(String name) {
this.name = Objects.requireNonNull(name);
}
public void print() {
printString(name);
}
private void printString(String s) {
System.out.println(s + " (" + s.length() + ")");
}
public static void main(String args) {
Printer printer = new Printer("123");
printer.print();
}
}
See also:
- Avoiding “!= null” statements in Java?
I still can't find the problem
If you tried to debug the problem and still don't have a solution, you can post a question for more help, but make sure to include what you've tried so far. At a minimum, include the stacktrace in the question, and mark the important line numbers in the code. Also, try simplifying the code first (see SSCCE).
39
+1 Good to have an example that includes going through the stacktrace; it's important to show why reading it is important for debugging NPE. (and why we almost always look for a stacktrace when someone posts a question about an error)
– Dennis Meng
Jun 8 '14 at 1:30
14
You mentioned debugging...How does that work? I have been researching the topic for a while now, but can find nothing. I'm sure an amazing teacher like you can teach it to me in a second! Thanks so much! :-)
– Ruchir Baronia
Dec 10 '15 at 7:07
13
@RuchirBaronia A debugger allows you to step through a program line by line to see which methods are called and how variables are changed. IDEs should have some tools to do this. See vogella.com/tutorials/EclipseDebugging/article.html for example.
– fgb
Dec 10 '15 at 10:22
13
@RuchirBaronia You set breakpoints on the methods around any NullPointerExceptions as seen in the stacktrace, and check the values of variables against what you expect them to be. If you know a variable is null when it shouldn't be, then you can set breakpoints around any code that changes the value. There are also conditional breakpoints you can use which will tell you when a value changes.
– fgb
Dec 10 '15 at 11:33
5
Setting String objects to an empty string as their default value is considered to be a poor practice.
– Tiny
Feb 27 '16 at 2:05
|
show 2 more comments
What is a NullPointerException?
A good place to start is the JavaDocs. They have this covered:
Thrown when an application attempts to use null in a case where an
object is required. These include:
- Calling the instance method of a null object.
- Accessing or modifying the field of a null object.
- Taking the length of null as if it were an array.
- Accessing or modifying the slots of null as if it were an array.
- Throwing null as if it were a Throwable value.
Applications should throw instances of this class to indicate other
illegal uses of the null object.
It is also the case that if you attempt to use a null reference with synchronized
, that will also throw this exception, per the JLS:
SynchronizedStatement:
synchronized ( Expression ) Block
- Otherwise, if the value of the Expression is null, a
NullPointerException
is thrown.
How do I fix it?
So you have a NullPointerException
. How do you fix it? Let's take a simple example which throws a NullPointerException
:
public class Printer {
private String name;
public void setName(String name) {
this.name = name;
}
public void print() {
printString(name);
}
private void printString(String s) {
System.out.println(s + " (" + s.length() + ")");
}
public static void main(String args) {
Printer printer = new Printer();
printer.print();
}
}
Identify the null values
The first step is identifying exactly which values are causing the exception. For this, we need to do some debugging. It's important to learn to read a stacktrace. This will show you where the exception was thrown:
Exception in thread "main" java.lang.NullPointerException
at Printer.printString(Printer.java:13)
at Printer.print(Printer.java:9)
at Printer.main(Printer.java:19)
Here, we see that the exception is thrown on line 13 (in the printString
method). Look at the line and check which values are null by
adding logging statements or using a debugger. We find out that s
is null, and calling the length
method on it throws the exception. We can see that the program stops throwing the exception when s.length()
is removed from the method.
Trace where these values come from
Next check where this value comes from. By following the callers of the method, we see that s
is passed in with printString(name)
in the print()
method, and this.name
is null.
Trace where these values should be set
Where is this.name
set? In the setName(String)
method. With some more debugging, we can see that this method isn't called at all. If the method was called, make sure to check the order that these methods are called, and the set method isn't called after the print method.
This is enough to give us a solution: add a call to printer.setName()
before calling printer.print()
.
Other fixes
The variable can have a default value (and setName
can prevent it being set to null):
private String name = "";
Either the print
or printString
method can check for null, for example:
printString((name == null) ? "" : name);
Or you can design the class so that name
always has a non-null value:
public class Printer {
private final String name;
public Printer(String name) {
this.name = Objects.requireNonNull(name);
}
public void print() {
printString(name);
}
private void printString(String s) {
System.out.println(s + " (" + s.length() + ")");
}
public static void main(String args) {
Printer printer = new Printer("123");
printer.print();
}
}
See also:
- Avoiding “!= null” statements in Java?
I still can't find the problem
If you tried to debug the problem and still don't have a solution, you can post a question for more help, but make sure to include what you've tried so far. At a minimum, include the stacktrace in the question, and mark the important line numbers in the code. Also, try simplifying the code first (see SSCCE).
39
+1 Good to have an example that includes going through the stacktrace; it's important to show why reading it is important for debugging NPE. (and why we almost always look for a stacktrace when someone posts a question about an error)
– Dennis Meng
Jun 8 '14 at 1:30
14
You mentioned debugging...How does that work? I have been researching the topic for a while now, but can find nothing. I'm sure an amazing teacher like you can teach it to me in a second! Thanks so much! :-)
– Ruchir Baronia
Dec 10 '15 at 7:07
13
@RuchirBaronia A debugger allows you to step through a program line by line to see which methods are called and how variables are changed. IDEs should have some tools to do this. See vogella.com/tutorials/EclipseDebugging/article.html for example.
– fgb
Dec 10 '15 at 10:22
13
@RuchirBaronia You set breakpoints on the methods around any NullPointerExceptions as seen in the stacktrace, and check the values of variables against what you expect them to be. If you know a variable is null when it shouldn't be, then you can set breakpoints around any code that changes the value. There are also conditional breakpoints you can use which will tell you when a value changes.
– fgb
Dec 10 '15 at 11:33
5
Setting String objects to an empty string as their default value is considered to be a poor practice.
– Tiny
Feb 27 '16 at 2:05
|
show 2 more comments
What is a NullPointerException?
A good place to start is the JavaDocs. They have this covered:
Thrown when an application attempts to use null in a case where an
object is required. These include:
- Calling the instance method of a null object.
- Accessing or modifying the field of a null object.
- Taking the length of null as if it were an array.
- Accessing or modifying the slots of null as if it were an array.
- Throwing null as if it were a Throwable value.
Applications should throw instances of this class to indicate other
illegal uses of the null object.
It is also the case that if you attempt to use a null reference with synchronized
, that will also throw this exception, per the JLS:
SynchronizedStatement:
synchronized ( Expression ) Block
- Otherwise, if the value of the Expression is null, a
NullPointerException
is thrown.
How do I fix it?
So you have a NullPointerException
. How do you fix it? Let's take a simple example which throws a NullPointerException
:
public class Printer {
private String name;
public void setName(String name) {
this.name = name;
}
public void print() {
printString(name);
}
private void printString(String s) {
System.out.println(s + " (" + s.length() + ")");
}
public static void main(String args) {
Printer printer = new Printer();
printer.print();
}
}
Identify the null values
The first step is identifying exactly which values are causing the exception. For this, we need to do some debugging. It's important to learn to read a stacktrace. This will show you where the exception was thrown:
Exception in thread "main" java.lang.NullPointerException
at Printer.printString(Printer.java:13)
at Printer.print(Printer.java:9)
at Printer.main(Printer.java:19)
Here, we see that the exception is thrown on line 13 (in the printString
method). Look at the line and check which values are null by
adding logging statements or using a debugger. We find out that s
is null, and calling the length
method on it throws the exception. We can see that the program stops throwing the exception when s.length()
is removed from the method.
Trace where these values come from
Next check where this value comes from. By following the callers of the method, we see that s
is passed in with printString(name)
in the print()
method, and this.name
is null.
Trace where these values should be set
Where is this.name
set? In the setName(String)
method. With some more debugging, we can see that this method isn't called at all. If the method was called, make sure to check the order that these methods are called, and the set method isn't called after the print method.
This is enough to give us a solution: add a call to printer.setName()
before calling printer.print()
.
Other fixes
The variable can have a default value (and setName
can prevent it being set to null):
private String name = "";
Either the print
or printString
method can check for null, for example:
printString((name == null) ? "" : name);
Or you can design the class so that name
always has a non-null value:
public class Printer {
private final String name;
public Printer(String name) {
this.name = Objects.requireNonNull(name);
}
public void print() {
printString(name);
}
private void printString(String s) {
System.out.println(s + " (" + s.length() + ")");
}
public static void main(String args) {
Printer printer = new Printer("123");
printer.print();
}
}
See also:
- Avoiding “!= null” statements in Java?
I still can't find the problem
If you tried to debug the problem and still don't have a solution, you can post a question for more help, but make sure to include what you've tried so far. At a minimum, include the stacktrace in the question, and mark the important line numbers in the code. Also, try simplifying the code first (see SSCCE).
What is a NullPointerException?
A good place to start is the JavaDocs. They have this covered:
Thrown when an application attempts to use null in a case where an
object is required. These include:
- Calling the instance method of a null object.
- Accessing or modifying the field of a null object.
- Taking the length of null as if it were an array.
- Accessing or modifying the slots of null as if it were an array.
- Throwing null as if it were a Throwable value.
Applications should throw instances of this class to indicate other
illegal uses of the null object.
It is also the case that if you attempt to use a null reference with synchronized
, that will also throw this exception, per the JLS:
SynchronizedStatement:
synchronized ( Expression ) Block
- Otherwise, if the value of the Expression is null, a
NullPointerException
is thrown.
How do I fix it?
So you have a NullPointerException
. How do you fix it? Let's take a simple example which throws a NullPointerException
:
public class Printer {
private String name;
public void setName(String name) {
this.name = name;
}
public void print() {
printString(name);
}
private void printString(String s) {
System.out.println(s + " (" + s.length() + ")");
}
public static void main(String args) {
Printer printer = new Printer();
printer.print();
}
}
Identify the null values
The first step is identifying exactly which values are causing the exception. For this, we need to do some debugging. It's important to learn to read a stacktrace. This will show you where the exception was thrown:
Exception in thread "main" java.lang.NullPointerException
at Printer.printString(Printer.java:13)
at Printer.print(Printer.java:9)
at Printer.main(Printer.java:19)
Here, we see that the exception is thrown on line 13 (in the printString
method). Look at the line and check which values are null by
adding logging statements or using a debugger. We find out that s
is null, and calling the length
method on it throws the exception. We can see that the program stops throwing the exception when s.length()
is removed from the method.
Trace where these values come from
Next check where this value comes from. By following the callers of the method, we see that s
is passed in with printString(name)
in the print()
method, and this.name
is null.
Trace where these values should be set
Where is this.name
set? In the setName(String)
method. With some more debugging, we can see that this method isn't called at all. If the method was called, make sure to check the order that these methods are called, and the set method isn't called after the print method.
This is enough to give us a solution: add a call to printer.setName()
before calling printer.print()
.
Other fixes
The variable can have a default value (and setName
can prevent it being set to null):
private String name = "";
Either the print
or printString
method can check for null, for example:
printString((name == null) ? "" : name);
Or you can design the class so that name
always has a non-null value:
public class Printer {
private final String name;
public Printer(String name) {
this.name = Objects.requireNonNull(name);
}
public void print() {
printString(name);
}
private void printString(String s) {
System.out.println(s + " (" + s.length() + ")");
}
public static void main(String args) {
Printer printer = new Printer("123");
printer.print();
}
}
See also:
- Avoiding “!= null” statements in Java?
I still can't find the problem
If you tried to debug the problem and still don't have a solution, you can post a question for more help, but make sure to include what you've tried so far. At a minimum, include the stacktrace in the question, and mark the important line numbers in the code. Also, try simplifying the code first (see SSCCE).
edited Dec 29 '17 at 13:53
community wiki
7 revs, 5 users 89%
fgb
39
+1 Good to have an example that includes going through the stacktrace; it's important to show why reading it is important for debugging NPE. (and why we almost always look for a stacktrace when someone posts a question about an error)
– Dennis Meng
Jun 8 '14 at 1:30
14
You mentioned debugging...How does that work? I have been researching the topic for a while now, but can find nothing. I'm sure an amazing teacher like you can teach it to me in a second! Thanks so much! :-)
– Ruchir Baronia
Dec 10 '15 at 7:07
13
@RuchirBaronia A debugger allows you to step through a program line by line to see which methods are called and how variables are changed. IDEs should have some tools to do this. See vogella.com/tutorials/EclipseDebugging/article.html for example.
– fgb
Dec 10 '15 at 10:22
13
@RuchirBaronia You set breakpoints on the methods around any NullPointerExceptions as seen in the stacktrace, and check the values of variables against what you expect them to be. If you know a variable is null when it shouldn't be, then you can set breakpoints around any code that changes the value. There are also conditional breakpoints you can use which will tell you when a value changes.
– fgb
Dec 10 '15 at 11:33
5
Setting String objects to an empty string as their default value is considered to be a poor practice.
– Tiny
Feb 27 '16 at 2:05
|
show 2 more comments
39
+1 Good to have an example that includes going through the stacktrace; it's important to show why reading it is important for debugging NPE. (and why we almost always look for a stacktrace when someone posts a question about an error)
– Dennis Meng
Jun 8 '14 at 1:30
14
You mentioned debugging...How does that work? I have been researching the topic for a while now, but can find nothing. I'm sure an amazing teacher like you can teach it to me in a second! Thanks so much! :-)
– Ruchir Baronia
Dec 10 '15 at 7:07
13
@RuchirBaronia A debugger allows you to step through a program line by line to see which methods are called and how variables are changed. IDEs should have some tools to do this. See vogella.com/tutorials/EclipseDebugging/article.html for example.
– fgb
Dec 10 '15 at 10:22
13
@RuchirBaronia You set breakpoints on the methods around any NullPointerExceptions as seen in the stacktrace, and check the values of variables against what you expect them to be. If you know a variable is null when it shouldn't be, then you can set breakpoints around any code that changes the value. There are also conditional breakpoints you can use which will tell you when a value changes.
– fgb
Dec 10 '15 at 11:33
5
Setting String objects to an empty string as their default value is considered to be a poor practice.
– Tiny
Feb 27 '16 at 2:05
39
39
+1 Good to have an example that includes going through the stacktrace; it's important to show why reading it is important for debugging NPE. (and why we almost always look for a stacktrace when someone posts a question about an error)
– Dennis Meng
Jun 8 '14 at 1:30
+1 Good to have an example that includes going through the stacktrace; it's important to show why reading it is important for debugging NPE. (and why we almost always look for a stacktrace when someone posts a question about an error)
– Dennis Meng
Jun 8 '14 at 1:30
14
14
You mentioned debugging...How does that work? I have been researching the topic for a while now, but can find nothing. I'm sure an amazing teacher like you can teach it to me in a second! Thanks so much! :-)
– Ruchir Baronia
Dec 10 '15 at 7:07
You mentioned debugging...How does that work? I have been researching the topic for a while now, but can find nothing. I'm sure an amazing teacher like you can teach it to me in a second! Thanks so much! :-)
– Ruchir Baronia
Dec 10 '15 at 7:07
13
13
@RuchirBaronia A debugger allows you to step through a program line by line to see which methods are called and how variables are changed. IDEs should have some tools to do this. See vogella.com/tutorials/EclipseDebugging/article.html for example.
– fgb
Dec 10 '15 at 10:22
@RuchirBaronia A debugger allows you to step through a program line by line to see which methods are called and how variables are changed. IDEs should have some tools to do this. See vogella.com/tutorials/EclipseDebugging/article.html for example.
– fgb
Dec 10 '15 at 10:22
13
13
@RuchirBaronia You set breakpoints on the methods around any NullPointerExceptions as seen in the stacktrace, and check the values of variables against what you expect them to be. If you know a variable is null when it shouldn't be, then you can set breakpoints around any code that changes the value. There are also conditional breakpoints you can use which will tell you when a value changes.
– fgb
Dec 10 '15 at 11:33
@RuchirBaronia You set breakpoints on the methods around any NullPointerExceptions as seen in the stacktrace, and check the values of variables against what you expect them to be. If you know a variable is null when it shouldn't be, then you can set breakpoints around any code that changes the value. There are also conditional breakpoints you can use which will tell you when a value changes.
– fgb
Dec 10 '15 at 11:33
5
5
Setting String objects to an empty string as their default value is considered to be a poor practice.
– Tiny
Feb 27 '16 at 2:05
Setting String objects to an empty string as their default value is considered to be a poor practice.
– Tiny
Feb 27 '16 at 2:05
|
show 2 more comments
Question: What causes a NullPointerException
(NPE)?
As you should know, Java types are divided into primitive types (boolean
, int
, etc.) and reference types. Reference types in Java allow you to use the special value null
which is the Java way of saying "no object".
A NullPointerException
is thrown at runtime whenever your program attempts to use a null
as if it was a real reference. For example, if you write this:
public class Test {
public static void main(String args) {
String foo = null;
int length = foo.length(); // HERE
}
}
the statement labelled "HERE" is going to attempt to run the length()
method on a null
reference, and this will throw a NullPointerException
.
There are many ways that you could use a null
value that will result in a NullPointerException
. In fact, the only things that you can do with a null
without causing an NPE are:
- assign it to a reference variable or read it from a reference variable,
- assign it to an array element or read it from an array element (provided that array reference itself is non-null!),
- pass it as a parameter or return it as a result, or
- test it using the
==
or!=
operators, orinstanceof
.
Question: How do I read the NPE stacktrace?
Suppose that I compile and run the program above:
$ javac Test.java
$ java Test
Exception in thread "main" java.lang.NullPointerException
at Test.main(Test.java:4)
$
First observation: the compilation succeeds! The problem in the program is NOT a compilation error. It is a runtime error. (Some IDEs may warn your program will always throw an exception ... but the standard javac
compiler doesn't.)
Second observation: when I run the program, it outputs two lines of "gobbledy-gook". WRONG!! That's not gobbledy-gook. It is a stacktrace ... and it provides vital information that will help you track down the error in your code, if you take the time to read it carefully.
So let's look at what it says:
Exception in thread "main" java.lang.NullPointerException
The first line of the stack trace tells you a number of things:
- It tells you the name of the Java thread in which the exception was thrown. For a simple program with one thread (like this one), it will be "main". Let's move on ...
- It tells you the full name of the exception that was thrown; i.e.
java.lang.NullPointerException
. - If the exception has an associated error message, that will be output after the exception name.
NullPointerException
is unusual in this respect, because it rarely has an error message.
The second line is the most important one in diagnosing an NPE.
at Test.main(Test.java:4)
This tells us a number of things:
- "at Test.main" says that we were in the
main
method of theTest
class. - "Test.java:4" gives the source filename of the class, AND it tells us that the statement where this occurred is in line 4 of the file.
If you count the lines in the file above, line 4 is the one that I labeled with the "HERE" comment.
Note that in a more complicated example, there will be lots of lines in the NPE stack trace. But you can be sure that the second line (the first "at" line) will tell you where the NPE was thrown1.
In short the stack trace will tell us unambiguously which statement of the program has thrown the NPE.
1 - Not quite true. There are things called nested exceptions...
Question: How do I track down the cause of the NPE exception in my code?
This is the hard part. The short answer is to apply logical inference to the evidence provided by the stack trace, the source code and the relevant API documentation.
Let's illustrate with the simple example (above) first. We start by looking at the line that the stack trace has told us is where the NPE happened:
int length = foo.length(); // HERE
How can that throw an NPE?
In fact there is only one way: it can only happen if foo
has the value null
. We then try to run the length()
method on null
and .... BANG!
But (I hear you say) what if the NPE was thrown inside the length()
method call?
Well, if that happened, the stack trace would look different. The first "at" line would say that the exception was thrown in some line in the java.lang.String
class, and line 4 of Test.java
would be the second "at" line.
So where did that null
come from? In this case it is obvious, and it is obvious what we need to do to fix it. (Assign a non-null value to foo
.)
OK, so let's try a slightly more tricky example. This will require some logical deduction.
public class Test {
private static String foo = new String[2];
private static int test(String bar, int pos) {
return bar[pos].length();
}
public static void main(String args) {
int length = test(foo, 1);
}
}
$ javac Test.java
$ java Test
Exception in thread "main" java.lang.NullPointerException
at Test.test(Test.java:6)
at Test.main(Test.java:10)
$
So now we have two "at" lines. The first one is for this line:
return args[pos].length();
and the second one is for this line:
int length = test(foo, 1);
Looking at the first line, how could that throw an NPE? There are two ways:
- If the value of
bar
isnull
thenbar[pos]
will throw an NPE. - If the value of
bar[pos]
isnull
then callinglength()
on it will throw an NPE.
Next, we need to figure out which of those scenarios explains what is actually happening. We will start by exploring the first one:
Where does bar
come from? It is a parameter to the test
method call, and if we look at how test
was called, we can see that it comes from the foo
static variable. In addition, we can see clearly that we initialized foo
to a non-null value. That is sufficient to tentatively dismiss this explanation. (In theory, something else could change foo
to null
... but that is not happening here.)
So what about our second scenario? Well, we can see that pos
is 1
, so that means that foo[1]
must be null
. Is that possible?
Indeed it is! And that is the problem. When we initialize like this:
private static String foo = new String[2];
we allocate a String
with two elements that are initialized to null
. After that, we have not changed the contents of foo
... so foo[1]
will still be null
.
add a comment |
Question: What causes a NullPointerException
(NPE)?
As you should know, Java types are divided into primitive types (boolean
, int
, etc.) and reference types. Reference types in Java allow you to use the special value null
which is the Java way of saying "no object".
A NullPointerException
is thrown at runtime whenever your program attempts to use a null
as if it was a real reference. For example, if you write this:
public class Test {
public static void main(String args) {
String foo = null;
int length = foo.length(); // HERE
}
}
the statement labelled "HERE" is going to attempt to run the length()
method on a null
reference, and this will throw a NullPointerException
.
There are many ways that you could use a null
value that will result in a NullPointerException
. In fact, the only things that you can do with a null
without causing an NPE are:
- assign it to a reference variable or read it from a reference variable,
- assign it to an array element or read it from an array element (provided that array reference itself is non-null!),
- pass it as a parameter or return it as a result, or
- test it using the
==
or!=
operators, orinstanceof
.
Question: How do I read the NPE stacktrace?
Suppose that I compile and run the program above:
$ javac Test.java
$ java Test
Exception in thread "main" java.lang.NullPointerException
at Test.main(Test.java:4)
$
First observation: the compilation succeeds! The problem in the program is NOT a compilation error. It is a runtime error. (Some IDEs may warn your program will always throw an exception ... but the standard javac
compiler doesn't.)
Second observation: when I run the program, it outputs two lines of "gobbledy-gook". WRONG!! That's not gobbledy-gook. It is a stacktrace ... and it provides vital information that will help you track down the error in your code, if you take the time to read it carefully.
So let's look at what it says:
Exception in thread "main" java.lang.NullPointerException
The first line of the stack trace tells you a number of things:
- It tells you the name of the Java thread in which the exception was thrown. For a simple program with one thread (like this one), it will be "main". Let's move on ...
- It tells you the full name of the exception that was thrown; i.e.
java.lang.NullPointerException
. - If the exception has an associated error message, that will be output after the exception name.
NullPointerException
is unusual in this respect, because it rarely has an error message.
The second line is the most important one in diagnosing an NPE.
at Test.main(Test.java:4)
This tells us a number of things:
- "at Test.main" says that we were in the
main
method of theTest
class. - "Test.java:4" gives the source filename of the class, AND it tells us that the statement where this occurred is in line 4 of the file.
If you count the lines in the file above, line 4 is the one that I labeled with the "HERE" comment.
Note that in a more complicated example, there will be lots of lines in the NPE stack trace. But you can be sure that the second line (the first "at" line) will tell you where the NPE was thrown1.
In short the stack trace will tell us unambiguously which statement of the program has thrown the NPE.
1 - Not quite true. There are things called nested exceptions...
Question: How do I track down the cause of the NPE exception in my code?
This is the hard part. The short answer is to apply logical inference to the evidence provided by the stack trace, the source code and the relevant API documentation.
Let's illustrate with the simple example (above) first. We start by looking at the line that the stack trace has told us is where the NPE happened:
int length = foo.length(); // HERE
How can that throw an NPE?
In fact there is only one way: it can only happen if foo
has the value null
. We then try to run the length()
method on null
and .... BANG!
But (I hear you say) what if the NPE was thrown inside the length()
method call?
Well, if that happened, the stack trace would look different. The first "at" line would say that the exception was thrown in some line in the java.lang.String
class, and line 4 of Test.java
would be the second "at" line.
So where did that null
come from? In this case it is obvious, and it is obvious what we need to do to fix it. (Assign a non-null value to foo
.)
OK, so let's try a slightly more tricky example. This will require some logical deduction.
public class Test {
private static String foo = new String[2];
private static int test(String bar, int pos) {
return bar[pos].length();
}
public static void main(String args) {
int length = test(foo, 1);
}
}
$ javac Test.java
$ java Test
Exception in thread "main" java.lang.NullPointerException
at Test.test(Test.java:6)
at Test.main(Test.java:10)
$
So now we have two "at" lines. The first one is for this line:
return args[pos].length();
and the second one is for this line:
int length = test(foo, 1);
Looking at the first line, how could that throw an NPE? There are two ways:
- If the value of
bar
isnull
thenbar[pos]
will throw an NPE. - If the value of
bar[pos]
isnull
then callinglength()
on it will throw an NPE.
Next, we need to figure out which of those scenarios explains what is actually happening. We will start by exploring the first one:
Where does bar
come from? It is a parameter to the test
method call, and if we look at how test
was called, we can see that it comes from the foo
static variable. In addition, we can see clearly that we initialized foo
to a non-null value. That is sufficient to tentatively dismiss this explanation. (In theory, something else could change foo
to null
... but that is not happening here.)
So what about our second scenario? Well, we can see that pos
is 1
, so that means that foo[1]
must be null
. Is that possible?
Indeed it is! And that is the problem. When we initialize like this:
private static String foo = new String[2];
we allocate a String
with two elements that are initialized to null
. After that, we have not changed the contents of foo
... so foo[1]
will still be null
.
add a comment |
Question: What causes a NullPointerException
(NPE)?
As you should know, Java types are divided into primitive types (boolean
, int
, etc.) and reference types. Reference types in Java allow you to use the special value null
which is the Java way of saying "no object".
A NullPointerException
is thrown at runtime whenever your program attempts to use a null
as if it was a real reference. For example, if you write this:
public class Test {
public static void main(String args) {
String foo = null;
int length = foo.length(); // HERE
}
}
the statement labelled "HERE" is going to attempt to run the length()
method on a null
reference, and this will throw a NullPointerException
.
There are many ways that you could use a null
value that will result in a NullPointerException
. In fact, the only things that you can do with a null
without causing an NPE are:
- assign it to a reference variable or read it from a reference variable,
- assign it to an array element or read it from an array element (provided that array reference itself is non-null!),
- pass it as a parameter or return it as a result, or
- test it using the
==
or!=
operators, orinstanceof
.
Question: How do I read the NPE stacktrace?
Suppose that I compile and run the program above:
$ javac Test.java
$ java Test
Exception in thread "main" java.lang.NullPointerException
at Test.main(Test.java:4)
$
First observation: the compilation succeeds! The problem in the program is NOT a compilation error. It is a runtime error. (Some IDEs may warn your program will always throw an exception ... but the standard javac
compiler doesn't.)
Second observation: when I run the program, it outputs two lines of "gobbledy-gook". WRONG!! That's not gobbledy-gook. It is a stacktrace ... and it provides vital information that will help you track down the error in your code, if you take the time to read it carefully.
So let's look at what it says:
Exception in thread "main" java.lang.NullPointerException
The first line of the stack trace tells you a number of things:
- It tells you the name of the Java thread in which the exception was thrown. For a simple program with one thread (like this one), it will be "main". Let's move on ...
- It tells you the full name of the exception that was thrown; i.e.
java.lang.NullPointerException
. - If the exception has an associated error message, that will be output after the exception name.
NullPointerException
is unusual in this respect, because it rarely has an error message.
The second line is the most important one in diagnosing an NPE.
at Test.main(Test.java:4)
This tells us a number of things:
- "at Test.main" says that we were in the
main
method of theTest
class. - "Test.java:4" gives the source filename of the class, AND it tells us that the statement where this occurred is in line 4 of the file.
If you count the lines in the file above, line 4 is the one that I labeled with the "HERE" comment.
Note that in a more complicated example, there will be lots of lines in the NPE stack trace. But you can be sure that the second line (the first "at" line) will tell you where the NPE was thrown1.
In short the stack trace will tell us unambiguously which statement of the program has thrown the NPE.
1 - Not quite true. There are things called nested exceptions...
Question: How do I track down the cause of the NPE exception in my code?
This is the hard part. The short answer is to apply logical inference to the evidence provided by the stack trace, the source code and the relevant API documentation.
Let's illustrate with the simple example (above) first. We start by looking at the line that the stack trace has told us is where the NPE happened:
int length = foo.length(); // HERE
How can that throw an NPE?
In fact there is only one way: it can only happen if foo
has the value null
. We then try to run the length()
method on null
and .... BANG!
But (I hear you say) what if the NPE was thrown inside the length()
method call?
Well, if that happened, the stack trace would look different. The first "at" line would say that the exception was thrown in some line in the java.lang.String
class, and line 4 of Test.java
would be the second "at" line.
So where did that null
come from? In this case it is obvious, and it is obvious what we need to do to fix it. (Assign a non-null value to foo
.)
OK, so let's try a slightly more tricky example. This will require some logical deduction.
public class Test {
private static String foo = new String[2];
private static int test(String bar, int pos) {
return bar[pos].length();
}
public static void main(String args) {
int length = test(foo, 1);
}
}
$ javac Test.java
$ java Test
Exception in thread "main" java.lang.NullPointerException
at Test.test(Test.java:6)
at Test.main(Test.java:10)
$
So now we have two "at" lines. The first one is for this line:
return args[pos].length();
and the second one is for this line:
int length = test(foo, 1);
Looking at the first line, how could that throw an NPE? There are two ways:
- If the value of
bar
isnull
thenbar[pos]
will throw an NPE. - If the value of
bar[pos]
isnull
then callinglength()
on it will throw an NPE.
Next, we need to figure out which of those scenarios explains what is actually happening. We will start by exploring the first one:
Where does bar
come from? It is a parameter to the test
method call, and if we look at how test
was called, we can see that it comes from the foo
static variable. In addition, we can see clearly that we initialized foo
to a non-null value. That is sufficient to tentatively dismiss this explanation. (In theory, something else could change foo
to null
... but that is not happening here.)
So what about our second scenario? Well, we can see that pos
is 1
, so that means that foo[1]
must be null
. Is that possible?
Indeed it is! And that is the problem. When we initialize like this:
private static String foo = new String[2];
we allocate a String
with two elements that are initialized to null
. After that, we have not changed the contents of foo
... so foo[1]
will still be null
.
Question: What causes a NullPointerException
(NPE)?
As you should know, Java types are divided into primitive types (boolean
, int
, etc.) and reference types. Reference types in Java allow you to use the special value null
which is the Java way of saying "no object".
A NullPointerException
is thrown at runtime whenever your program attempts to use a null
as if it was a real reference. For example, if you write this:
public class Test {
public static void main(String args) {
String foo = null;
int length = foo.length(); // HERE
}
}
the statement labelled "HERE" is going to attempt to run the length()
method on a null
reference, and this will throw a NullPointerException
.
There are many ways that you could use a null
value that will result in a NullPointerException
. In fact, the only things that you can do with a null
without causing an NPE are:
- assign it to a reference variable or read it from a reference variable,
- assign it to an array element or read it from an array element (provided that array reference itself is non-null!),
- pass it as a parameter or return it as a result, or
- test it using the
==
or!=
operators, orinstanceof
.
Question: How do I read the NPE stacktrace?
Suppose that I compile and run the program above:
$ javac Test.java
$ java Test
Exception in thread "main" java.lang.NullPointerException
at Test.main(Test.java:4)
$
First observation: the compilation succeeds! The problem in the program is NOT a compilation error. It is a runtime error. (Some IDEs may warn your program will always throw an exception ... but the standard javac
compiler doesn't.)
Second observation: when I run the program, it outputs two lines of "gobbledy-gook". WRONG!! That's not gobbledy-gook. It is a stacktrace ... and it provides vital information that will help you track down the error in your code, if you take the time to read it carefully.
So let's look at what it says:
Exception in thread "main" java.lang.NullPointerException
The first line of the stack trace tells you a number of things:
- It tells you the name of the Java thread in which the exception was thrown. For a simple program with one thread (like this one), it will be "main". Let's move on ...
- It tells you the full name of the exception that was thrown; i.e.
java.lang.NullPointerException
. - If the exception has an associated error message, that will be output after the exception name.
NullPointerException
is unusual in this respect, because it rarely has an error message.
The second line is the most important one in diagnosing an NPE.
at Test.main(Test.java:4)
This tells us a number of things:
- "at Test.main" says that we were in the
main
method of theTest
class. - "Test.java:4" gives the source filename of the class, AND it tells us that the statement where this occurred is in line 4 of the file.
If you count the lines in the file above, line 4 is the one that I labeled with the "HERE" comment.
Note that in a more complicated example, there will be lots of lines in the NPE stack trace. But you can be sure that the second line (the first "at" line) will tell you where the NPE was thrown1.
In short the stack trace will tell us unambiguously which statement of the program has thrown the NPE.
1 - Not quite true. There are things called nested exceptions...
Question: How do I track down the cause of the NPE exception in my code?
This is the hard part. The short answer is to apply logical inference to the evidence provided by the stack trace, the source code and the relevant API documentation.
Let's illustrate with the simple example (above) first. We start by looking at the line that the stack trace has told us is where the NPE happened:
int length = foo.length(); // HERE
How can that throw an NPE?
In fact there is only one way: it can only happen if foo
has the value null
. We then try to run the length()
method on null
and .... BANG!
But (I hear you say) what if the NPE was thrown inside the length()
method call?
Well, if that happened, the stack trace would look different. The first "at" line would say that the exception was thrown in some line in the java.lang.String
class, and line 4 of Test.java
would be the second "at" line.
So where did that null
come from? In this case it is obvious, and it is obvious what we need to do to fix it. (Assign a non-null value to foo
.)
OK, so let's try a slightly more tricky example. This will require some logical deduction.
public class Test {
private static String foo = new String[2];
private static int test(String bar, int pos) {
return bar[pos].length();
}
public static void main(String args) {
int length = test(foo, 1);
}
}
$ javac Test.java
$ java Test
Exception in thread "main" java.lang.NullPointerException
at Test.test(Test.java:6)
at Test.main(Test.java:10)
$
So now we have two "at" lines. The first one is for this line:
return args[pos].length();
and the second one is for this line:
int length = test(foo, 1);
Looking at the first line, how could that throw an NPE? There are two ways:
- If the value of
bar
isnull
thenbar[pos]
will throw an NPE. - If the value of
bar[pos]
isnull
then callinglength()
on it will throw an NPE.
Next, we need to figure out which of those scenarios explains what is actually happening. We will start by exploring the first one:
Where does bar
come from? It is a parameter to the test
method call, and if we look at how test
was called, we can see that it comes from the foo
static variable. In addition, we can see clearly that we initialized foo
to a non-null value. That is sufficient to tentatively dismiss this explanation. (In theory, something else could change foo
to null
... but that is not happening here.)
So what about our second scenario? Well, we can see that pos
is 1
, so that means that foo[1]
must be null
. Is that possible?
Indeed it is! And that is the problem. When we initialize like this:
private static String foo = new String[2];
we allocate a String
with two elements that are initialized to null
. After that, we have not changed the contents of foo
... so foo[1]
will still be null
.
edited Mar 19 '18 at 14:05
community wiki
10 revs, 6 users 87%
Stephen C
add a comment |
add a comment |
It's like you are trying to access an object which is null
. Consider below example:
TypeA objA;
At this time you have just declared this object but not initialized or instantiated. And whenever you try to access any property or method in it, it will throw NullPointerException
which makes sense.
See this below example as well:
String a = null;
System.out.println(a.toString()); // NullPointerException will be thrown
If we give System.out.println(a.length()); // NullPointerException will be thrown, to skip this we can handle with try catch block. thank you
– Varma
Feb 7 at 7:25
add a comment |
It's like you are trying to access an object which is null
. Consider below example:
TypeA objA;
At this time you have just declared this object but not initialized or instantiated. And whenever you try to access any property or method in it, it will throw NullPointerException
which makes sense.
See this below example as well:
String a = null;
System.out.println(a.toString()); // NullPointerException will be thrown
If we give System.out.println(a.length()); // NullPointerException will be thrown, to skip this we can handle with try catch block. thank you
– Varma
Feb 7 at 7:25
add a comment |
It's like you are trying to access an object which is null
. Consider below example:
TypeA objA;
At this time you have just declared this object but not initialized or instantiated. And whenever you try to access any property or method in it, it will throw NullPointerException
which makes sense.
See this below example as well:
String a = null;
System.out.println(a.toString()); // NullPointerException will be thrown
It's like you are trying to access an object which is null
. Consider below example:
TypeA objA;
At this time you have just declared this object but not initialized or instantiated. And whenever you try to access any property or method in it, it will throw NullPointerException
which makes sense.
See this below example as well:
String a = null;
System.out.println(a.toString()); // NullPointerException will be thrown
edited May 15 '18 at 14:58
community wiki
5 revs, 5 users 38%
Rakesh Burbure
If we give System.out.println(a.length()); // NullPointerException will be thrown, to skip this we can handle with try catch block. thank you
– Varma
Feb 7 at 7:25
add a comment |
If we give System.out.println(a.length()); // NullPointerException will be thrown, to skip this we can handle with try catch block. thank you
– Varma
Feb 7 at 7:25
If we give System.out.println(a.length()); // NullPointerException will be thrown, to skip this we can handle with try catch block. thank you
– Varma
Feb 7 at 7:25
If we give System.out.println(a.length()); // NullPointerException will be thrown, to skip this we can handle with try catch block. thank you
– Varma
Feb 7 at 7:25
add a comment |
A null pointer exception is thrown when an application attempts to use null in a case where an object is required. These include:
- Calling the instance method of a
null
object. - Accessing or modifying the field of a
null
object. - Taking the length of
null
as if it were an array. - Accessing or modifying the slots of
null
as if it were an array. - Throwing
null
as if it were a Throwable value.
Applications should throw instances of this class to indicate other illegal uses of the null
object.
Reference: http://docs.oracle.com/javase/8/docs/api/java/lang/NullPointerException.html
11
Keep it simple, I like this answer, add this if you consider correct - Access to uninitialized attribute of an object
– Emiliano
Mar 23 '16 at 13:06
5
@Emiliano - simply accessing an initialized attribute does not cause an NPE. It is what you >>do<< with the uninitialized attribute value that causes the NPE.
– Stephen C
May 19 '16 at 6:57
8
This is from docs.oracle.com/javase/8/docs/api/java/lang/…. -1 for quoting without reference.
– Dominique Unruh
Sep 18 '16 at 17:07
1
If you want more cases: 1) using anull
as the target of asynchronized
block, 2) using anull
as the target of aswitch
, and unboxingnull
.
– Stephen C
Oct 23 '17 at 10:16
add a comment |
A null pointer exception is thrown when an application attempts to use null in a case where an object is required. These include:
- Calling the instance method of a
null
object. - Accessing or modifying the field of a
null
object. - Taking the length of
null
as if it were an array. - Accessing or modifying the slots of
null
as if it were an array. - Throwing
null
as if it were a Throwable value.
Applications should throw instances of this class to indicate other illegal uses of the null
object.
Reference: http://docs.oracle.com/javase/8/docs/api/java/lang/NullPointerException.html
11
Keep it simple, I like this answer, add this if you consider correct - Access to uninitialized attribute of an object
– Emiliano
Mar 23 '16 at 13:06
5
@Emiliano - simply accessing an initialized attribute does not cause an NPE. It is what you >>do<< with the uninitialized attribute value that causes the NPE.
– Stephen C
May 19 '16 at 6:57
8
This is from docs.oracle.com/javase/8/docs/api/java/lang/…. -1 for quoting without reference.
– Dominique Unruh
Sep 18 '16 at 17:07
1
If you want more cases: 1) using anull
as the target of asynchronized
block, 2) using anull
as the target of aswitch
, and unboxingnull
.
– Stephen C
Oct 23 '17 at 10:16
add a comment |
A null pointer exception is thrown when an application attempts to use null in a case where an object is required. These include:
- Calling the instance method of a
null
object. - Accessing or modifying the field of a
null
object. - Taking the length of
null
as if it were an array. - Accessing or modifying the slots of
null
as if it were an array. - Throwing
null
as if it were a Throwable value.
Applications should throw instances of this class to indicate other illegal uses of the null
object.
Reference: http://docs.oracle.com/javase/8/docs/api/java/lang/NullPointerException.html
A null pointer exception is thrown when an application attempts to use null in a case where an object is required. These include:
- Calling the instance method of a
null
object. - Accessing or modifying the field of a
null
object. - Taking the length of
null
as if it were an array. - Accessing or modifying the slots of
null
as if it were an array. - Throwing
null
as if it were a Throwable value.
Applications should throw instances of this class to indicate other illegal uses of the null
object.
Reference: http://docs.oracle.com/javase/8/docs/api/java/lang/NullPointerException.html
edited Dec 20 '17 at 21:40
community wiki
5 revs, 4 users 55%
nathan1138
11
Keep it simple, I like this answer, add this if you consider correct - Access to uninitialized attribute of an object
– Emiliano
Mar 23 '16 at 13:06
5
@Emiliano - simply accessing an initialized attribute does not cause an NPE. It is what you >>do<< with the uninitialized attribute value that causes the NPE.
– Stephen C
May 19 '16 at 6:57
8
This is from docs.oracle.com/javase/8/docs/api/java/lang/…. -1 for quoting without reference.
– Dominique Unruh
Sep 18 '16 at 17:07
1
If you want more cases: 1) using anull
as the target of asynchronized
block, 2) using anull
as the target of aswitch
, and unboxingnull
.
– Stephen C
Oct 23 '17 at 10:16
add a comment |
11
Keep it simple, I like this answer, add this if you consider correct - Access to uninitialized attribute of an object
– Emiliano
Mar 23 '16 at 13:06
5
@Emiliano - simply accessing an initialized attribute does not cause an NPE. It is what you >>do<< with the uninitialized attribute value that causes the NPE.
– Stephen C
May 19 '16 at 6:57
8
This is from docs.oracle.com/javase/8/docs/api/java/lang/…. -1 for quoting without reference.
– Dominique Unruh
Sep 18 '16 at 17:07
1
If you want more cases: 1) using anull
as the target of asynchronized
block, 2) using anull
as the target of aswitch
, and unboxingnull
.
– Stephen C
Oct 23 '17 at 10:16
11
11
Keep it simple, I like this answer, add this if you consider correct - Access to uninitialized attribute of an object
– Emiliano
Mar 23 '16 at 13:06
Keep it simple, I like this answer, add this if you consider correct - Access to uninitialized attribute of an object
– Emiliano
Mar 23 '16 at 13:06
5
5
@Emiliano - simply accessing an initialized attribute does not cause an NPE. It is what you >>do<< with the uninitialized attribute value that causes the NPE.
– Stephen C
May 19 '16 at 6:57
@Emiliano - simply accessing an initialized attribute does not cause an NPE. It is what you >>do<< with the uninitialized attribute value that causes the NPE.
– Stephen C
May 19 '16 at 6:57
8
8
This is from docs.oracle.com/javase/8/docs/api/java/lang/…. -1 for quoting without reference.
– Dominique Unruh
Sep 18 '16 at 17:07
This is from docs.oracle.com/javase/8/docs/api/java/lang/…. -1 for quoting without reference.
– Dominique Unruh
Sep 18 '16 at 17:07
1
1
If you want more cases: 1) using a
null
as the target of a synchronized
block, 2) using a null
as the target of a switch
, and unboxing null
.– Stephen C
Oct 23 '17 at 10:16
If you want more cases: 1) using a
null
as the target of a synchronized
block, 2) using a null
as the target of a switch
, and unboxing null
.– Stephen C
Oct 23 '17 at 10:16
add a comment |
A NULL
pointer is one that points to nowhere. When you dereference a pointer p
, you say "give me the data at the location stored in "p". When p
is a null pointer, the location stored in p
is nowhere
, you're saying "give me the data at the location 'nowhere'". Obviously, it can't do this, so it throws a NULL pointer exception
.
In general, it's because something hasn't been initialized properly.
1
Are we creating a database ? -->NULL
is written asnull
in java. And it's a case sensitive thing.
– bvdb
Apr 25 '18 at 16:40
Lol. @bvdb Chill.
– TheRealChx101
Sep 8 '18 at 22:45
2
"A NULL pointer is one that points to nowhere" I disagree. Null pointers don't point to nowhere, they point to null values.
– TheRealChx101
Sep 8 '18 at 22:46
1
@TheRealChx101 A null pointer and a pointer to a null value are different things - a null pointer does not point to a null value. Suppose you have a pointer to a pointer: pointer A points to pointer B, and pointer B is null. In this case, pointer A points to a null value, and pointer B is a null pointer.
– MrZebra
Sep 10 '18 at 7:43
add a comment |
A NULL
pointer is one that points to nowhere. When you dereference a pointer p
, you say "give me the data at the location stored in "p". When p
is a null pointer, the location stored in p
is nowhere
, you're saying "give me the data at the location 'nowhere'". Obviously, it can't do this, so it throws a NULL pointer exception
.
In general, it's because something hasn't been initialized properly.
1
Are we creating a database ? -->NULL
is written asnull
in java. And it's a case sensitive thing.
– bvdb
Apr 25 '18 at 16:40
Lol. @bvdb Chill.
– TheRealChx101
Sep 8 '18 at 22:45
2
"A NULL pointer is one that points to nowhere" I disagree. Null pointers don't point to nowhere, they point to null values.
– TheRealChx101
Sep 8 '18 at 22:46
1
@TheRealChx101 A null pointer and a pointer to a null value are different things - a null pointer does not point to a null value. Suppose you have a pointer to a pointer: pointer A points to pointer B, and pointer B is null. In this case, pointer A points to a null value, and pointer B is a null pointer.
– MrZebra
Sep 10 '18 at 7:43
add a comment |
A NULL
pointer is one that points to nowhere. When you dereference a pointer p
, you say "give me the data at the location stored in "p". When p
is a null pointer, the location stored in p
is nowhere
, you're saying "give me the data at the location 'nowhere'". Obviously, it can't do this, so it throws a NULL pointer exception
.
In general, it's because something hasn't been initialized properly.
A NULL
pointer is one that points to nowhere. When you dereference a pointer p
, you say "give me the data at the location stored in "p". When p
is a null pointer, the location stored in p
is nowhere
, you're saying "give me the data at the location 'nowhere'". Obviously, it can't do this, so it throws a NULL pointer exception
.
In general, it's because something hasn't been initialized properly.
edited Dec 25 '17 at 14:30
community wiki
4 revs, 4 users 57%
MrZebra
1
Are we creating a database ? -->NULL
is written asnull
in java. And it's a case sensitive thing.
– bvdb
Apr 25 '18 at 16:40
Lol. @bvdb Chill.
– TheRealChx101
Sep 8 '18 at 22:45
2
"A NULL pointer is one that points to nowhere" I disagree. Null pointers don't point to nowhere, they point to null values.
– TheRealChx101
Sep 8 '18 at 22:46
1
@TheRealChx101 A null pointer and a pointer to a null value are different things - a null pointer does not point to a null value. Suppose you have a pointer to a pointer: pointer A points to pointer B, and pointer B is null. In this case, pointer A points to a null value, and pointer B is a null pointer.
– MrZebra
Sep 10 '18 at 7:43
add a comment |
1
Are we creating a database ? -->NULL
is written asnull
in java. And it's a case sensitive thing.
– bvdb
Apr 25 '18 at 16:40
Lol. @bvdb Chill.
– TheRealChx101
Sep 8 '18 at 22:45
2
"A NULL pointer is one that points to nowhere" I disagree. Null pointers don't point to nowhere, they point to null values.
– TheRealChx101
Sep 8 '18 at 22:46
1
@TheRealChx101 A null pointer and a pointer to a null value are different things - a null pointer does not point to a null value. Suppose you have a pointer to a pointer: pointer A points to pointer B, and pointer B is null. In this case, pointer A points to a null value, and pointer B is a null pointer.
– MrZebra
Sep 10 '18 at 7:43
1
1
Are we creating a database ? -->
NULL
is written as null
in java. And it's a case sensitive thing.– bvdb
Apr 25 '18 at 16:40
Are we creating a database ? -->
NULL
is written as null
in java. And it's a case sensitive thing.– bvdb
Apr 25 '18 at 16:40
Lol. @bvdb Chill.
– TheRealChx101
Sep 8 '18 at 22:45
Lol. @bvdb Chill.
– TheRealChx101
Sep 8 '18 at 22:45
2
2
"A NULL pointer is one that points to nowhere" I disagree. Null pointers don't point to nowhere, they point to null values.
– TheRealChx101
Sep 8 '18 at 22:46
"A NULL pointer is one that points to nowhere" I disagree. Null pointers don't point to nowhere, they point to null values.
– TheRealChx101
Sep 8 '18 at 22:46
1
1
@TheRealChx101 A null pointer and a pointer to a null value are different things - a null pointer does not point to a null value. Suppose you have a pointer to a pointer: pointer A points to pointer B, and pointer B is null. In this case, pointer A points to a null value, and pointer B is a null pointer.
– MrZebra
Sep 10 '18 at 7:43
@TheRealChx101 A null pointer and a pointer to a null value are different things - a null pointer does not point to a null value. Suppose you have a pointer to a pointer: pointer A points to pointer B, and pointer B is null. In this case, pointer A points to a null value, and pointer B is a null pointer.
– MrZebra
Sep 10 '18 at 7:43
add a comment |
A lot of explanations are already present to explain how it happens and how to fix it, but you should also follow best practices to avoid NullPointerException
at all.
See also:
A good list of best practices
I would add, very important, make a good use of the final
modifier.
Using the "final" modifier whenever applicable in Java
Summary:
- Use the
final
modifier to enforce good initialization. - Avoid returning null in methods, for example returning empty collections when applicable.
- Use annotations
@NotNull
and@Nullable
- Fail fast and use asserts to avoid propagation of null objects through the whole application when they shouldn't be null.
- Use equals with a known object first:
if("knownObject".equals(unknownObject)
- Prefer
valueOf()
over toString(). - Use null safe
StringUtils
methodsStringUtils.isEmpty(null)
.
3
In j2ee projects,Nullpointer exception is very common.Some cases reference variables got null values.So You should check the variable initialization properly.And during conditional statement you should always check that flag or reference contains null or not like:- if(flag!=0) { ur code that uses flag }
– Amaresh Pattanayak
Apr 17 '15 at 12:58
12
It is worth mentioning that some IDEs (e.g. Eclipse) offer automatic nullity analisys based on customizable annotations (e.g.@Nullable
as listed above) and warn about potential errors. It is also possible to infer and generate such annotations (e.g. IntelliJ can do that) based on existing code structure.
– Jan Chimiak
Mar 5 '16 at 10:34
3
First thing should do is before using a nullable object, you should check whether is it null, usingif (obj==null)
.If it is null then you should write code to handle that also.
– Lakmal Vithanage
Feb 17 '17 at 6:52
3
IMO, it is preferable to avoid returning null objects in methods when possible and use annotation when null input parameters are not allowed in order to, by contract, reduce the amount of ´if (obj==null)´ in the code and improve the code readability.
– L. G.
Feb 27 '17 at 9:43
3
Read this ... before you accept these "best practices" as truth: satisfice.com/blog/archives/27
– Stephen C
May 21 '17 at 7:52
|
show 3 more comments
A lot of explanations are already present to explain how it happens and how to fix it, but you should also follow best practices to avoid NullPointerException
at all.
See also:
A good list of best practices
I would add, very important, make a good use of the final
modifier.
Using the "final" modifier whenever applicable in Java
Summary:
- Use the
final
modifier to enforce good initialization. - Avoid returning null in methods, for example returning empty collections when applicable.
- Use annotations
@NotNull
and@Nullable
- Fail fast and use asserts to avoid propagation of null objects through the whole application when they shouldn't be null.
- Use equals with a known object first:
if("knownObject".equals(unknownObject)
- Prefer
valueOf()
over toString(). - Use null safe
StringUtils
methodsStringUtils.isEmpty(null)
.
3
In j2ee projects,Nullpointer exception is very common.Some cases reference variables got null values.So You should check the variable initialization properly.And during conditional statement you should always check that flag or reference contains null or not like:- if(flag!=0) { ur code that uses flag }
– Amaresh Pattanayak
Apr 17 '15 at 12:58
12
It is worth mentioning that some IDEs (e.g. Eclipse) offer automatic nullity analisys based on customizable annotations (e.g.@Nullable
as listed above) and warn about potential errors. It is also possible to infer and generate such annotations (e.g. IntelliJ can do that) based on existing code structure.
– Jan Chimiak
Mar 5 '16 at 10:34
3
First thing should do is before using a nullable object, you should check whether is it null, usingif (obj==null)
.If it is null then you should write code to handle that also.
– Lakmal Vithanage
Feb 17 '17 at 6:52
3
IMO, it is preferable to avoid returning null objects in methods when possible and use annotation when null input parameters are not allowed in order to, by contract, reduce the amount of ´if (obj==null)´ in the code and improve the code readability.
– L. G.
Feb 27 '17 at 9:43
3
Read this ... before you accept these "best practices" as truth: satisfice.com/blog/archives/27
– Stephen C
May 21 '17 at 7:52
|
show 3 more comments
A lot of explanations are already present to explain how it happens and how to fix it, but you should also follow best practices to avoid NullPointerException
at all.
See also:
A good list of best practices
I would add, very important, make a good use of the final
modifier.
Using the "final" modifier whenever applicable in Java
Summary:
- Use the
final
modifier to enforce good initialization. - Avoid returning null in methods, for example returning empty collections when applicable.
- Use annotations
@NotNull
and@Nullable
- Fail fast and use asserts to avoid propagation of null objects through the whole application when they shouldn't be null.
- Use equals with a known object first:
if("knownObject".equals(unknownObject)
- Prefer
valueOf()
over toString(). - Use null safe
StringUtils
methodsStringUtils.isEmpty(null)
.
A lot of explanations are already present to explain how it happens and how to fix it, but you should also follow best practices to avoid NullPointerException
at all.
See also:
A good list of best practices
I would add, very important, make a good use of the final
modifier.
Using the "final" modifier whenever applicable in Java
Summary:
- Use the
final
modifier to enforce good initialization. - Avoid returning null in methods, for example returning empty collections when applicable.
- Use annotations
@NotNull
and@Nullable
- Fail fast and use asserts to avoid propagation of null objects through the whole application when they shouldn't be null.
- Use equals with a known object first:
if("knownObject".equals(unknownObject)
- Prefer
valueOf()
over toString(). - Use null safe
StringUtils
methodsStringUtils.isEmpty(null)
.
edited Dec 25 '17 at 14:31
community wiki
5 revs, 4 users 68%
L. G.
3
In j2ee projects,Nullpointer exception is very common.Some cases reference variables got null values.So You should check the variable initialization properly.And during conditional statement you should always check that flag or reference contains null or not like:- if(flag!=0) { ur code that uses flag }
– Amaresh Pattanayak
Apr 17 '15 at 12:58
12
It is worth mentioning that some IDEs (e.g. Eclipse) offer automatic nullity analisys based on customizable annotations (e.g.@Nullable
as listed above) and warn about potential errors. It is also possible to infer and generate such annotations (e.g. IntelliJ can do that) based on existing code structure.
– Jan Chimiak
Mar 5 '16 at 10:34
3
First thing should do is before using a nullable object, you should check whether is it null, usingif (obj==null)
.If it is null then you should write code to handle that also.
– Lakmal Vithanage
Feb 17 '17 at 6:52
3
IMO, it is preferable to avoid returning null objects in methods when possible and use annotation when null input parameters are not allowed in order to, by contract, reduce the amount of ´if (obj==null)´ in the code and improve the code readability.
– L. G.
Feb 27 '17 at 9:43
3
Read this ... before you accept these "best practices" as truth: satisfice.com/blog/archives/27
– Stephen C
May 21 '17 at 7:52
|
show 3 more comments
3
In j2ee projects,Nullpointer exception is very common.Some cases reference variables got null values.So You should check the variable initialization properly.And during conditional statement you should always check that flag or reference contains null or not like:- if(flag!=0) { ur code that uses flag }
– Amaresh Pattanayak
Apr 17 '15 at 12:58
12
It is worth mentioning that some IDEs (e.g. Eclipse) offer automatic nullity analisys based on customizable annotations (e.g.@Nullable
as listed above) and warn about potential errors. It is also possible to infer and generate such annotations (e.g. IntelliJ can do that) based on existing code structure.
– Jan Chimiak
Mar 5 '16 at 10:34
3
First thing should do is before using a nullable object, you should check whether is it null, usingif (obj==null)
.If it is null then you should write code to handle that also.
– Lakmal Vithanage
Feb 17 '17 at 6:52
3
IMO, it is preferable to avoid returning null objects in methods when possible and use annotation when null input parameters are not allowed in order to, by contract, reduce the amount of ´if (obj==null)´ in the code and improve the code readability.
– L. G.
Feb 27 '17 at 9:43
3
Read this ... before you accept these "best practices" as truth: satisfice.com/blog/archives/27
– Stephen C
May 21 '17 at 7:52
3
3
In j2ee projects,Nullpointer exception is very common.Some cases reference variables got null values.So You should check the variable initialization properly.And during conditional statement you should always check that flag or reference contains null or not like:- if(flag!=0) { ur code that uses flag }
– Amaresh Pattanayak
Apr 17 '15 at 12:58
In j2ee projects,Nullpointer exception is very common.Some cases reference variables got null values.So You should check the variable initialization properly.And during conditional statement you should always check that flag or reference contains null or not like:- if(flag!=0) { ur code that uses flag }
– Amaresh Pattanayak
Apr 17 '15 at 12:58
12
12
It is worth mentioning that some IDEs (e.g. Eclipse) offer automatic nullity analisys based on customizable annotations (e.g.
@Nullable
as listed above) and warn about potential errors. It is also possible to infer and generate such annotations (e.g. IntelliJ can do that) based on existing code structure.– Jan Chimiak
Mar 5 '16 at 10:34
It is worth mentioning that some IDEs (e.g. Eclipse) offer automatic nullity analisys based on customizable annotations (e.g.
@Nullable
as listed above) and warn about potential errors. It is also possible to infer and generate such annotations (e.g. IntelliJ can do that) based on existing code structure.– Jan Chimiak
Mar 5 '16 at 10:34
3
3
First thing should do is before using a nullable object, you should check whether is it null, using
if (obj==null)
.If it is null then you should write code to handle that also.– Lakmal Vithanage
Feb 17 '17 at 6:52
First thing should do is before using a nullable object, you should check whether is it null, using
if (obj==null)
.If it is null then you should write code to handle that also.– Lakmal Vithanage
Feb 17 '17 at 6:52
3
3
IMO, it is preferable to avoid returning null objects in methods when possible and use annotation when null input parameters are not allowed in order to, by contract, reduce the amount of ´if (obj==null)´ in the code and improve the code readability.
– L. G.
Feb 27 '17 at 9:43
IMO, it is preferable to avoid returning null objects in methods when possible and use annotation when null input parameters are not allowed in order to, by contract, reduce the amount of ´if (obj==null)´ in the code and improve the code readability.
– L. G.
Feb 27 '17 at 9:43
3
3
Read this ... before you accept these "best practices" as truth: satisfice.com/blog/archives/27
– Stephen C
May 21 '17 at 7:52
Read this ... before you accept these "best practices" as truth: satisfice.com/blog/archives/27
– Stephen C
May 21 '17 at 7:52
|
show 3 more comments
A null pointer exception is an indicator that you are using an object without initializing it.
For example, below is a student class which will use it in our code.
public class Student {
private int id;
public int getId() {
return this.id;
}
public setId(int newId) {
this.id = newId;
}
}
The below code gives you a null pointer exception.
public class School {
Student obj_Student;
public School() {
try {
obj_Student.getId();
}
catch(Exception e) {
System.out.println("Null Pointer ");
}
}
}
Because you are using Obj_Student
, but you forgot to initialize it like in the
correct code shown below:
public class School {
Student obj_Student;
public School() {
try {
obj_Student = new Student();
obj_Student.setId(12);
obj_Student.getId();
}
catch(Exception e) {
System.out.println("Null Pointer ");
}
}
}
7
While this is a nice example, may I ask what it adds to the question that isn't already covered by all the other answers?
– Mysticial
Sep 24 '13 at 6:20
13
It is simply inappropriate to use the word "uninitialized" here. The example you shown is in fact "initialized", and it is initialized with null. For uninitialized variables, compiler will complain to you.
– Adrian Shum
Sep 24 '13 at 6:32
2
An NPE may be an indicator that you are using an uninitialized field. It may be an indicator that you are doing other things. Oversimplifying to a single cause like this does not help someone solve NPE problems ... if the actual cause is not this one.
– Stephen C
May 27 '15 at 13:35
add a comment |
A null pointer exception is an indicator that you are using an object without initializing it.
For example, below is a student class which will use it in our code.
public class Student {
private int id;
public int getId() {
return this.id;
}
public setId(int newId) {
this.id = newId;
}
}
The below code gives you a null pointer exception.
public class School {
Student obj_Student;
public School() {
try {
obj_Student.getId();
}
catch(Exception e) {
System.out.println("Null Pointer ");
}
}
}
Because you are using Obj_Student
, but you forgot to initialize it like in the
correct code shown below:
public class School {
Student obj_Student;
public School() {
try {
obj_Student = new Student();
obj_Student.setId(12);
obj_Student.getId();
}
catch(Exception e) {
System.out.println("Null Pointer ");
}
}
}
7
While this is a nice example, may I ask what it adds to the question that isn't already covered by all the other answers?
– Mysticial
Sep 24 '13 at 6:20
13
It is simply inappropriate to use the word "uninitialized" here. The example you shown is in fact "initialized", and it is initialized with null. For uninitialized variables, compiler will complain to you.
– Adrian Shum
Sep 24 '13 at 6:32
2
An NPE may be an indicator that you are using an uninitialized field. It may be an indicator that you are doing other things. Oversimplifying to a single cause like this does not help someone solve NPE problems ... if the actual cause is not this one.
– Stephen C
May 27 '15 at 13:35
add a comment |
A null pointer exception is an indicator that you are using an object without initializing it.
For example, below is a student class which will use it in our code.
public class Student {
private int id;
public int getId() {
return this.id;
}
public setId(int newId) {
this.id = newId;
}
}
The below code gives you a null pointer exception.
public class School {
Student obj_Student;
public School() {
try {
obj_Student.getId();
}
catch(Exception e) {
System.out.println("Null Pointer ");
}
}
}
Because you are using Obj_Student
, but you forgot to initialize it like in the
correct code shown below:
public class School {
Student obj_Student;
public School() {
try {
obj_Student = new Student();
obj_Student.setId(12);
obj_Student.getId();
}
catch(Exception e) {
System.out.println("Null Pointer ");
}
}
}
A null pointer exception is an indicator that you are using an object without initializing it.
For example, below is a student class which will use it in our code.
public class Student {
private int id;
public int getId() {
return this.id;
}
public setId(int newId) {
this.id = newId;
}
}
The below code gives you a null pointer exception.
public class School {
Student obj_Student;
public School() {
try {
obj_Student.getId();
}
catch(Exception e) {
System.out.println("Null Pointer ");
}
}
}
Because you are using Obj_Student
, but you forgot to initialize it like in the
correct code shown below:
public class School {
Student obj_Student;
public School() {
try {
obj_Student = new Student();
obj_Student.setId(12);
obj_Student.getId();
}
catch(Exception e) {
System.out.println("Null Pointer ");
}
}
}
edited Dec 20 '17 at 21:44
community wiki
5 revs, 4 users 61%
javid piprani
7
While this is a nice example, may I ask what it adds to the question that isn't already covered by all the other answers?
– Mysticial
Sep 24 '13 at 6:20
13
It is simply inappropriate to use the word "uninitialized" here. The example you shown is in fact "initialized", and it is initialized with null. For uninitialized variables, compiler will complain to you.
– Adrian Shum
Sep 24 '13 at 6:32
2
An NPE may be an indicator that you are using an uninitialized field. It may be an indicator that you are doing other things. Oversimplifying to a single cause like this does not help someone solve NPE problems ... if the actual cause is not this one.
– Stephen C
May 27 '15 at 13:35
add a comment |
7
While this is a nice example, may I ask what it adds to the question that isn't already covered by all the other answers?
– Mysticial
Sep 24 '13 at 6:20
13
It is simply inappropriate to use the word "uninitialized" here. The example you shown is in fact "initialized", and it is initialized with null. For uninitialized variables, compiler will complain to you.
– Adrian Shum
Sep 24 '13 at 6:32
2
An NPE may be an indicator that you are using an uninitialized field. It may be an indicator that you are doing other things. Oversimplifying to a single cause like this does not help someone solve NPE problems ... if the actual cause is not this one.
– Stephen C
May 27 '15 at 13:35
7
7
While this is a nice example, may I ask what it adds to the question that isn't already covered by all the other answers?
– Mysticial
Sep 24 '13 at 6:20
While this is a nice example, may I ask what it adds to the question that isn't already covered by all the other answers?
– Mysticial
Sep 24 '13 at 6:20
13
13
It is simply inappropriate to use the word "uninitialized" here. The example you shown is in fact "initialized", and it is initialized with null. For uninitialized variables, compiler will complain to you.
– Adrian Shum
Sep 24 '13 at 6:32
It is simply inappropriate to use the word "uninitialized" here. The example you shown is in fact "initialized", and it is initialized with null. For uninitialized variables, compiler will complain to you.
– Adrian Shum
Sep 24 '13 at 6:32
2
2
An NPE may be an indicator that you are using an uninitialized field. It may be an indicator that you are doing other things. Oversimplifying to a single cause like this does not help someone solve NPE problems ... if the actual cause is not this one.
– Stephen C
May 27 '15 at 13:35
An NPE may be an indicator that you are using an uninitialized field. It may be an indicator that you are doing other things. Oversimplifying to a single cause like this does not help someone solve NPE problems ... if the actual cause is not this one.
– Stephen C
May 27 '15 at 13:35
add a comment |
In Java, everything is in the form of a class.
If you want to use any object then you have two phases:
- Declare
- Initialization
Example:
- Declaration:
Object a;
- Initialization:
a=new Object();
Same for the array concept
- Declaration:
Item i=new Item[5];
- Initialization:
i[0]=new Item();
If you are not giving the initialization section then the NullpointerException
arise.
15
Declaring a primitive variable, such as an int, in Java does not create an Object.
– Michael Krause
Nov 15 '16 at 21:44
3
A NullPointerException often occurs when calling method of an instance.For example, if you declare a reference but does not make it point to any instance, NullPointerException will happen when you call its method. such as: YourClass ref = null; // or ref = anotherRef; // but anotherRef has not pointed any instance ref.someMethod(); // it will throw NullPointerException. Generally fix it in this way: Before the method is called, determine whether the reference is null. such as: if (yourRef != null) { yourRef.someMethod(); }
– sunhang
Jul 28 '17 at 10:25
2
Or use exception capture: such as: try { yourRef.someMethod(); } catch (NullPointerException e) { // TODO }
– sunhang
Jul 28 '17 at 10:25
add a comment |
In Java, everything is in the form of a class.
If you want to use any object then you have two phases:
- Declare
- Initialization
Example:
- Declaration:
Object a;
- Initialization:
a=new Object();
Same for the array concept
- Declaration:
Item i=new Item[5];
- Initialization:
i[0]=new Item();
If you are not giving the initialization section then the NullpointerException
arise.
15
Declaring a primitive variable, such as an int, in Java does not create an Object.
– Michael Krause
Nov 15 '16 at 21:44
3
A NullPointerException often occurs when calling method of an instance.For example, if you declare a reference but does not make it point to any instance, NullPointerException will happen when you call its method. such as: YourClass ref = null; // or ref = anotherRef; // but anotherRef has not pointed any instance ref.someMethod(); // it will throw NullPointerException. Generally fix it in this way: Before the method is called, determine whether the reference is null. such as: if (yourRef != null) { yourRef.someMethod(); }
– sunhang
Jul 28 '17 at 10:25
2
Or use exception capture: such as: try { yourRef.someMethod(); } catch (NullPointerException e) { // TODO }
– sunhang
Jul 28 '17 at 10:25
add a comment |
In Java, everything is in the form of a class.
If you want to use any object then you have two phases:
- Declare
- Initialization
Example:
- Declaration:
Object a;
- Initialization:
a=new Object();
Same for the array concept
- Declaration:
Item i=new Item[5];
- Initialization:
i[0]=new Item();
If you are not giving the initialization section then the NullpointerException
arise.
In Java, everything is in the form of a class.
If you want to use any object then you have two phases:
- Declare
- Initialization
Example:
- Declaration:
Object a;
- Initialization:
a=new Object();
Same for the array concept
- Declaration:
Item i=new Item[5];
- Initialization:
i[0]=new Item();
If you are not giving the initialization section then the NullpointerException
arise.
edited Jun 22 '18 at 0:34
community wiki
5 revs, 5 users 58%
ashish bhatt
15
Declaring a primitive variable, such as an int, in Java does not create an Object.
– Michael Krause
Nov 15 '16 at 21:44
3
A NullPointerException often occurs when calling method of an instance.For example, if you declare a reference but does not make it point to any instance, NullPointerException will happen when you call its method. such as: YourClass ref = null; // or ref = anotherRef; // but anotherRef has not pointed any instance ref.someMethod(); // it will throw NullPointerException. Generally fix it in this way: Before the method is called, determine whether the reference is null. such as: if (yourRef != null) { yourRef.someMethod(); }
– sunhang
Jul 28 '17 at 10:25
2
Or use exception capture: such as: try { yourRef.someMethod(); } catch (NullPointerException e) { // TODO }
– sunhang
Jul 28 '17 at 10:25
add a comment |
15
Declaring a primitive variable, such as an int, in Java does not create an Object.
– Michael Krause
Nov 15 '16 at 21:44
3
A NullPointerException often occurs when calling method of an instance.For example, if you declare a reference but does not make it point to any instance, NullPointerException will happen when you call its method. such as: YourClass ref = null; // or ref = anotherRef; // but anotherRef has not pointed any instance ref.someMethod(); // it will throw NullPointerException. Generally fix it in this way: Before the method is called, determine whether the reference is null. such as: if (yourRef != null) { yourRef.someMethod(); }
– sunhang
Jul 28 '17 at 10:25
2
Or use exception capture: such as: try { yourRef.someMethod(); } catch (NullPointerException e) { // TODO }
– sunhang
Jul 28 '17 at 10:25
15
15
Declaring a primitive variable, such as an int, in Java does not create an Object.
– Michael Krause
Nov 15 '16 at 21:44
Declaring a primitive variable, such as an int, in Java does not create an Object.
– Michael Krause
Nov 15 '16 at 21:44
3
3
A NullPointerException often occurs when calling method of an instance.For example, if you declare a reference but does not make it point to any instance, NullPointerException will happen when you call its method. such as: YourClass ref = null; // or ref = anotherRef; // but anotherRef has not pointed any instance ref.someMethod(); // it will throw NullPointerException. Generally fix it in this way: Before the method is called, determine whether the reference is null. such as: if (yourRef != null) { yourRef.someMethod(); }
– sunhang
Jul 28 '17 at 10:25
A NullPointerException often occurs when calling method of an instance.For example, if you declare a reference but does not make it point to any instance, NullPointerException will happen when you call its method. such as: YourClass ref = null; // or ref = anotherRef; // but anotherRef has not pointed any instance ref.someMethod(); // it will throw NullPointerException. Generally fix it in this way: Before the method is called, determine whether the reference is null. such as: if (yourRef != null) { yourRef.someMethod(); }
– sunhang
Jul 28 '17 at 10:25
2
2
Or use exception capture: such as: try { yourRef.someMethod(); } catch (NullPointerException e) { // TODO }
– sunhang
Jul 28 '17 at 10:25
Or use exception capture: such as: try { yourRef.someMethod(); } catch (NullPointerException e) { // TODO }
– sunhang
Jul 28 '17 at 10:25
add a comment |
In Java all the variables you declare are actually "references" to the objects (or primitives) and not the objects themselves.
When you attempt to execute one object method, the reference asks the living object to execute that method. But if the reference is referencing NULL (nothing, zero, void, nada) then there is no way the method gets executed. Then the runtime let you know this by throwing a NullPointerException.
Your reference is "pointing" to null, thus "Null -> Pointer".
The object lives in the VM memory space and the only way to access it is using this
references. Take this example:
public class Some {
private int id;
public int getId(){
return this.id;
}
public setId( int newId ) {
this.id = newId;
}
}
And on another place in your code:
Some reference = new Some(); // Point to a new object of type Some()
Some otherReference = null; // Initiallly this points to NULL
reference.setId( 1 ); // Execute setId method, now private var id is 1
System.out.println( reference.getId() ); // Prints 1 to the console
otherReference = reference // Now they both point to the only object.
reference = null; // "reference" now point to null.
// But "otherReference" still point to the "real" object so this print 1 too...
System.out.println( otherReference.getId() );
// Guess what will happen
System.out.println( reference.getId() ); // :S Throws NullPointerException because "reference" is pointing to NULL remember...
This an important thing to know - when there are no more references to an object (in the example above when reference
and otherReference
both point to null) then the object is "unreachable". There is no way we can work with it, so this object is ready to be garbage collected, and at some point, the VM will free the memory used by this object and will allocate another.
add a comment |
In Java all the variables you declare are actually "references" to the objects (or primitives) and not the objects themselves.
When you attempt to execute one object method, the reference asks the living object to execute that method. But if the reference is referencing NULL (nothing, zero, void, nada) then there is no way the method gets executed. Then the runtime let you know this by throwing a NullPointerException.
Your reference is "pointing" to null, thus "Null -> Pointer".
The object lives in the VM memory space and the only way to access it is using this
references. Take this example:
public class Some {
private int id;
public int getId(){
return this.id;
}
public setId( int newId ) {
this.id = newId;
}
}
And on another place in your code:
Some reference = new Some(); // Point to a new object of type Some()
Some otherReference = null; // Initiallly this points to NULL
reference.setId( 1 ); // Execute setId method, now private var id is 1
System.out.println( reference.getId() ); // Prints 1 to the console
otherReference = reference // Now they both point to the only object.
reference = null; // "reference" now point to null.
// But "otherReference" still point to the "real" object so this print 1 too...
System.out.println( otherReference.getId() );
// Guess what will happen
System.out.println( reference.getId() ); // :S Throws NullPointerException because "reference" is pointing to NULL remember...
This an important thing to know - when there are no more references to an object (in the example above when reference
and otherReference
both point to null) then the object is "unreachable". There is no way we can work with it, so this object is ready to be garbage collected, and at some point, the VM will free the memory used by this object and will allocate another.
add a comment |
In Java all the variables you declare are actually "references" to the objects (or primitives) and not the objects themselves.
When you attempt to execute one object method, the reference asks the living object to execute that method. But if the reference is referencing NULL (nothing, zero, void, nada) then there is no way the method gets executed. Then the runtime let you know this by throwing a NullPointerException.
Your reference is "pointing" to null, thus "Null -> Pointer".
The object lives in the VM memory space and the only way to access it is using this
references. Take this example:
public class Some {
private int id;
public int getId(){
return this.id;
}
public setId( int newId ) {
this.id = newId;
}
}
And on another place in your code:
Some reference = new Some(); // Point to a new object of type Some()
Some otherReference = null; // Initiallly this points to NULL
reference.setId( 1 ); // Execute setId method, now private var id is 1
System.out.println( reference.getId() ); // Prints 1 to the console
otherReference = reference // Now they both point to the only object.
reference = null; // "reference" now point to null.
// But "otherReference" still point to the "real" object so this print 1 too...
System.out.println( otherReference.getId() );
// Guess what will happen
System.out.println( reference.getId() ); // :S Throws NullPointerException because "reference" is pointing to NULL remember...
This an important thing to know - when there are no more references to an object (in the example above when reference
and otherReference
both point to null) then the object is "unreachable". There is no way we can work with it, so this object is ready to be garbage collected, and at some point, the VM will free the memory used by this object and will allocate another.
In Java all the variables you declare are actually "references" to the objects (or primitives) and not the objects themselves.
When you attempt to execute one object method, the reference asks the living object to execute that method. But if the reference is referencing NULL (nothing, zero, void, nada) then there is no way the method gets executed. Then the runtime let you know this by throwing a NullPointerException.
Your reference is "pointing" to null, thus "Null -> Pointer".
The object lives in the VM memory space and the only way to access it is using this
references. Take this example:
public class Some {
private int id;
public int getId(){
return this.id;
}
public setId( int newId ) {
this.id = newId;
}
}
And on another place in your code:
Some reference = new Some(); // Point to a new object of type Some()
Some otherReference = null; // Initiallly this points to NULL
reference.setId( 1 ); // Execute setId method, now private var id is 1
System.out.println( reference.getId() ); // Prints 1 to the console
otherReference = reference // Now they both point to the only object.
reference = null; // "reference" now point to null.
// But "otherReference" still point to the "real" object so this print 1 too...
System.out.println( otherReference.getId() );
// Guess what will happen
System.out.println( reference.getId() ); // :S Throws NullPointerException because "reference" is pointing to NULL remember...
This an important thing to know - when there are no more references to an object (in the example above when reference
and otherReference
both point to null) then the object is "unreachable". There is no way we can work with it, so this object is ready to be garbage collected, and at some point, the VM will free the memory used by this object and will allocate another.
edited Aug 10 '18 at 7:52
community wiki
4 revs, 4 users 79%
OscarRyz
add a comment |
add a comment |
Another occurrence of a NullPointerException
occurs when one declares an object array, then immediately tries to dereference elements inside of it.
String phrases = new String[10];
String keyPhrase = "Bird";
for(String phrase : phrases) {
System.out.println(phrase.equals(keyPhrase));
}
This particular NPE can be avoided if the comparison order is reversed; namely, use .equals
on a guaranteed non-null object.
All elements inside of an array are initialized to their common initial value; for any type of object array, that means that all elements are null
.
You must initialize the elements in the array before accessing or dereferencing them.
String phrases = new String {"The bird", "A bird", "My bird", "Bird"};
String keyPhrase = "Bird";
for(String phrase : phrases) {
System.out.println(phrase.equals(keyPhrase));
}
operation on uninitialized object at instance level(not the class level) will lead to NullPointerException. operation need to be instance specific. if operation is at class level, saying calling a static method on uninitialized object then it will not throw NullPointerException exception. Even primitive wrapper class objects throws NullPointerException.
– Shailendra Singh
Jul 8 '16 at 15:20
1. NullPointerException is a RuntimeException, that means will appear when your program is running, you will not at compilation time.! :(, but most of the IDE help you to discover this. 2. Minimize the use of the keyword 'null' in assignment statements. :) Reference url:
– tomj0101
Dec 4 '17 at 5:49
@tomj0101 I'm thoroughly unclear as to why you made that comment... But to your second point, a pattern beforeOptional
was to return null. The keyword is fine. Knowing how to guard against it is critical. This offers one common occurrence of it and ways to mitigate it.
– Makoto
Dec 4 '17 at 5:54
NullPointerException is a run-time exception which is not recommended to catch it, but instead avoid it.
– Shomu
May 29 '18 at 10:14
@Shomu: At what point do I even suggest that it should be caught?
– Makoto
May 29 '18 at 13:25
add a comment |
Another occurrence of a NullPointerException
occurs when one declares an object array, then immediately tries to dereference elements inside of it.
String phrases = new String[10];
String keyPhrase = "Bird";
for(String phrase : phrases) {
System.out.println(phrase.equals(keyPhrase));
}
This particular NPE can be avoided if the comparison order is reversed; namely, use .equals
on a guaranteed non-null object.
All elements inside of an array are initialized to their common initial value; for any type of object array, that means that all elements are null
.
You must initialize the elements in the array before accessing or dereferencing them.
String phrases = new String {"The bird", "A bird", "My bird", "Bird"};
String keyPhrase = "Bird";
for(String phrase : phrases) {
System.out.println(phrase.equals(keyPhrase));
}
operation on uninitialized object at instance level(not the class level) will lead to NullPointerException. operation need to be instance specific. if operation is at class level, saying calling a static method on uninitialized object then it will not throw NullPointerException exception. Even primitive wrapper class objects throws NullPointerException.
– Shailendra Singh
Jul 8 '16 at 15:20
1. NullPointerException is a RuntimeException, that means will appear when your program is running, you will not at compilation time.! :(, but most of the IDE help you to discover this. 2. Minimize the use of the keyword 'null' in assignment statements. :) Reference url:
– tomj0101
Dec 4 '17 at 5:49
@tomj0101 I'm thoroughly unclear as to why you made that comment... But to your second point, a pattern beforeOptional
was to return null. The keyword is fine. Knowing how to guard against it is critical. This offers one common occurrence of it and ways to mitigate it.
– Makoto
Dec 4 '17 at 5:54
NullPointerException is a run-time exception which is not recommended to catch it, but instead avoid it.
– Shomu
May 29 '18 at 10:14
@Shomu: At what point do I even suggest that it should be caught?
– Makoto
May 29 '18 at 13:25
add a comment |
Another occurrence of a NullPointerException
occurs when one declares an object array, then immediately tries to dereference elements inside of it.
String phrases = new String[10];
String keyPhrase = "Bird";
for(String phrase : phrases) {
System.out.println(phrase.equals(keyPhrase));
}
This particular NPE can be avoided if the comparison order is reversed; namely, use .equals
on a guaranteed non-null object.
All elements inside of an array are initialized to their common initial value; for any type of object array, that means that all elements are null
.
You must initialize the elements in the array before accessing or dereferencing them.
String phrases = new String {"The bird", "A bird", "My bird", "Bird"};
String keyPhrase = "Bird";
for(String phrase : phrases) {
System.out.println(phrase.equals(keyPhrase));
}
Another occurrence of a NullPointerException
occurs when one declares an object array, then immediately tries to dereference elements inside of it.
String phrases = new String[10];
String keyPhrase = "Bird";
for(String phrase : phrases) {
System.out.println(phrase.equals(keyPhrase));
}
This particular NPE can be avoided if the comparison order is reversed; namely, use .equals
on a guaranteed non-null object.
All elements inside of an array are initialized to their common initial value; for any type of object array, that means that all elements are null
.
You must initialize the elements in the array before accessing or dereferencing them.
String phrases = new String {"The bird", "A bird", "My bird", "Bird"};
String keyPhrase = "Bird";
for(String phrase : phrases) {
System.out.println(phrase.equals(keyPhrase));
}
edited Dec 25 '17 at 14:35
community wiki
2 revs, 2 users 97%
Makoto
operation on uninitialized object at instance level(not the class level) will lead to NullPointerException. operation need to be instance specific. if operation is at class level, saying calling a static method on uninitialized object then it will not throw NullPointerException exception. Even primitive wrapper class objects throws NullPointerException.
– Shailendra Singh
Jul 8 '16 at 15:20
1. NullPointerException is a RuntimeException, that means will appear when your program is running, you will not at compilation time.! :(, but most of the IDE help you to discover this. 2. Minimize the use of the keyword 'null' in assignment statements. :) Reference url:
– tomj0101
Dec 4 '17 at 5:49
@tomj0101 I'm thoroughly unclear as to why you made that comment... But to your second point, a pattern beforeOptional
was to return null. The keyword is fine. Knowing how to guard against it is critical. This offers one common occurrence of it and ways to mitigate it.
– Makoto
Dec 4 '17 at 5:54
NullPointerException is a run-time exception which is not recommended to catch it, but instead avoid it.
– Shomu
May 29 '18 at 10:14
@Shomu: At what point do I even suggest that it should be caught?
– Makoto
May 29 '18 at 13:25
add a comment |
operation on uninitialized object at instance level(not the class level) will lead to NullPointerException. operation need to be instance specific. if operation is at class level, saying calling a static method on uninitialized object then it will not throw NullPointerException exception. Even primitive wrapper class objects throws NullPointerException.
– Shailendra Singh
Jul 8 '16 at 15:20
1. NullPointerException is a RuntimeException, that means will appear when your program is running, you will not at compilation time.! :(, but most of the IDE help you to discover this. 2. Minimize the use of the keyword 'null' in assignment statements. :) Reference url:
– tomj0101
Dec 4 '17 at 5:49
@tomj0101 I'm thoroughly unclear as to why you made that comment... But to your second point, a pattern beforeOptional
was to return null. The keyword is fine. Knowing how to guard against it is critical. This offers one common occurrence of it and ways to mitigate it.
– Makoto
Dec 4 '17 at 5:54
NullPointerException is a run-time exception which is not recommended to catch it, but instead avoid it.
– Shomu
May 29 '18 at 10:14
@Shomu: At what point do I even suggest that it should be caught?
– Makoto
May 29 '18 at 13:25
operation on uninitialized object at instance level(not the class level) will lead to NullPointerException. operation need to be instance specific. if operation is at class level, saying calling a static method on uninitialized object then it will not throw NullPointerException exception. Even primitive wrapper class objects throws NullPointerException.
– Shailendra Singh
Jul 8 '16 at 15:20
operation on uninitialized object at instance level(not the class level) will lead to NullPointerException. operation need to be instance specific. if operation is at class level, saying calling a static method on uninitialized object then it will not throw NullPointerException exception. Even primitive wrapper class objects throws NullPointerException.
– Shailendra Singh
Jul 8 '16 at 15:20
1. NullPointerException is a RuntimeException, that means will appear when your program is running, you will not at compilation time.! :(, but most of the IDE help you to discover this. 2. Minimize the use of the keyword 'null' in assignment statements. :) Reference url:
– tomj0101
Dec 4 '17 at 5:49
1. NullPointerException is a RuntimeException, that means will appear when your program is running, you will not at compilation time.! :(, but most of the IDE help you to discover this. 2. Minimize the use of the keyword 'null' in assignment statements. :) Reference url:
– tomj0101
Dec 4 '17 at 5:49
@tomj0101 I'm thoroughly unclear as to why you made that comment... But to your second point, a pattern before
Optional
was to return null. The keyword is fine. Knowing how to guard against it is critical. This offers one common occurrence of it and ways to mitigate it.– Makoto
Dec 4 '17 at 5:54
@tomj0101 I'm thoroughly unclear as to why you made that comment... But to your second point, a pattern before
Optional
was to return null. The keyword is fine. Knowing how to guard against it is critical. This offers one common occurrence of it and ways to mitigate it.– Makoto
Dec 4 '17 at 5:54
NullPointerException is a run-time exception which is not recommended to catch it, but instead avoid it.
– Shomu
May 29 '18 at 10:14
NullPointerException is a run-time exception which is not recommended to catch it, but instead avoid it.
– Shomu
May 29 '18 at 10:14
@Shomu: At what point do I even suggest that it should be caught?
– Makoto
May 29 '18 at 13:25
@Shomu: At what point do I even suggest that it should be caught?
– Makoto
May 29 '18 at 13:25
add a comment |