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?
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?
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 sometime you write code that does not directly create the object.
For instance you may have a method as follows:
public void doSomething(Integer num){
//do something to num
}
in which case you are not creating the object num, rather assuming that is was created before the doSomething method was called. Unfortunately it is possible to call the method like this:
doSomething(null);
In which case num is null. The best way to avoid this type of exception is to always check for null when you did not create the object yourself. So doSomething should be re-written as:
public void doSomething(Integer num){
if(num != null){
//do something to num
}
}
Finally, How to pinpoint the exception location & cause using Stack Trace
They're 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 NPE. 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 NPE 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 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 NPE 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.)
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.
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 lea 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 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().
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:
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).
A null pointer exception is caused when you dereference a variable that is pointing to null. See the following code:
String a = null;
System.out.println(a.toString()); // NullPointerException will be thrown
NullPointerException?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. If fact, the only things that you can do with a null without causing an NPE are:
== or != operators, or instanceof.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 wa your program will always throw an exception ... but the standard javac compiler doesn't.)
Second observation: when I run the program, it outputs too 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 lets look at what is says:
Exception in thread "main" java.lang.NullPointerException
The first line of the stack trace tells you a number of things:
java.lang.NullPointerException.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:
main method of the Test class.And if you count the lines in the file above, line 4 is the one that I labelled 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 stacktrace will tell us unambiguously which statement of the program has thrown the NPE.
1 - Not quite true. There are things called nested exceptions ...
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.
Lets illustrate with the simple example (above) first. We start by looking at the line that the stacktrace 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 stacktrace 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 lets 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) {
retu 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 2 "at" lines. The first one is for this line:
retu args[pos].length();
and the second one is for this line:
int length = test(foo, 1);
So looking at the first line, how could that throw an NPE? In fact, there are two ways:
bar is null then bar[pos] will throw an NPE.bar[pos] is null then calling length() on it will throw an NPE.So next we need to figure out which of those scenarios explains what is actually happening. Lets 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. And 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's not happening here.)
So what about our 2nd 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. And then we didn't change the contents of foo ... so foo[1] will still be null.
Null pointer exception is thrown when an application attempts to use null in a case where an object is required. These include:
Applications should throw instances of this class to indicate other illegal uses of the null object.
In Java every things is in the form of class.
If you want to use any object then you have two phases
Example:
int a;a=0;Same for Array concept
Item i[]=new Item[5];i[0]=new Item();If you not given Initialization section then the NullpointerException arise.
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.
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 ask 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(){
retu this.id;
}
public setId( int newId ) {
this.id = newId;
}
}
....
....
// Somewhere else...
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" point to null) then the object is "unreachable". There is no way we can work with it, so this object is marked for to be garbage collected, and at some point the VM will free the memory used by this object and will allocate another.
A null pointer exception is an indicator that you are using Object without initialize it.
e.g below is a student class which will use in our code.
public class student {
private int id;
public int getId(){
retu this.id;
}
public setId( int newId ) {
this.id = newId;
}
}
below code give you 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 wise correct code is 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 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.
A good list of best practices is for example here:
http://javarevisited.blogspot.com/2013/05/ava-tips-and-best-practices-to-avoid-nullpointerexception-program-application.html
I would add, very important, make a good use of the final modifier.
Using "final" modifier whenever applicable in java
Summary:
final modifier to enforce good initialization.@NotNull and @Nullableif("knownObject".equals(unknownObject)valueOf() over toString().StringUtils methods StringUtils.isEmpty(null).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 derefencing 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));
}
برچسب:
نویسنده: استخدام کار