What is a NullPointerException, and how do I fix it?
Asked Answered
M

12

209

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?

Mealymouthed answered 20/10, 2008 at 13:18 Comment(0)
A
4195

There are two overarching types of variables in Java:

  1. Primitives: variables that contain data. If you want to manipulate the data in a primitive variable you can manipulate that variable directly. By convention primitive types start with a lowercase letter. For example variables of type int or char are primitives.

  2. References: variables that contain the memory address of an Object i.e. variables that refer to an Object. If you want to manipulate the Object that a reference variable refers to you must dereference it. Dereferencing usually entails using . to access a method or field, or using [ to index an array. By convention reference types are usually denoted with a type that starts in uppercase. For example variables of type Object are references.

Consider the following code where you declare a variable of primitive type int and don't initialize it:

int x;
int y = x + x;

These two lines will crash the program because no value is specified for x and we are trying to use x's value to specify y. All primitives have to be initialized to a usable value before they are manipulated.

Now here is where things get interesting. Reference variables can be set to null which means "I am referencing nothing". You can get a null value in a reference variable if you explicitly set it that way, or a reference variable is uninitialized and the compiler does not catch it (Java will automatically set the variable to null).

If a reference variable is set to null either explicitly by you or through Java automatically, and you attempt to dereference it you get a NullPointerException.

The NullPointerException (NPE) typically occurs when you declare a variable but did not create an object and assign it to the variable before trying to use the contents of the variable. So you have a reference to something that does not actually exist.

Take the following code:

Integer num;
num = new Integer(10);

The first line declares a variable named num, but it does not actually contain a reference value yet. Since you have not yet said what to point to, Java sets it to null.

In the second line, the new keyword is used to instantiate (or create) an object of type Integer, and the reference variable num is assigned to that Integer 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 may 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, assumes obj is not null
   obj.myMethod();
}

In which case, you are not creating the object obj, but rather assuming that it was created before the doSomething() method was called. Note, it is possible to call the method like this:

doSomething(null);

In which case, obj is null, and the statement obj.myMethod() will throw a NullPointerException.

If the method is intended to do something to the passed-in object as the above method does, it is appropriate to throw the NullPointerException because it's a programmer error and the programmer will need that information for debugging purposes.

In addition to NullPointerExceptions thrown as a result of the method's logic, you can also check the method arguments for null values and throw NPEs explicitly by adding something like the following near the beginning of a method:

// Throws an NPE with a custom error message if obj is null
Objects.requireNonNull(obj, "obj must not be null");

Note that it's helpful to say in your error message clearly which object cannot be null. The advantage of validating this is that 1) you can return your own clearer error messages and 2) for the rest of the method you know that unless obj is reassigned, it is not null and can be dereferenced safely.

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

What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?

Sonar with find bugs can detect NPE. Can sonar catch null pointer exceptions caused by JVM Dynamically

Now Java 14 has added a new language feature to show the root cause of NullPointerException. This language feature has been part of SAP commercial JVM since 2006.

In Java 14, the following is a sample NullPointerException Exception message:

in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.List.size()" because "list" is null

List of situations that cause a NullPointerException to occur

Here are all the situations in which a NullPointerException occurs, that are directly* mentioned by the Java Language Specification:

  • Accessing (i.e. getting or setting) an instance field of a null reference. (static fields don't count!)
  • Calling an instance method of a null reference. (static methods don't count!)
  • throw null;
  • Accessing elements of a null array.
  • Synchronising on null - synchronized (someNullReference) { ... }
  • Any integer/floating point operator can throw a NullPointerException if one of its operands is a boxed null reference
  • An unboxing conversion throws a NullPointerException if the boxed value is null.
  • Calling super on a null reference throws a NullPointerException. If you are confused, this is talking about qualified superclass constructor invocations:
class Outer {
    class Inner {}
}
class ChildOfInner extends Outer.Inner {
    ChildOfInner(Outer o) { 
        o.super(); // if o is null, NPE gets thrown
    }
}
  • Using a for (element : iterable) loop to loop through a null collection/array.

  • switch (foo) { ... } (whether its an expression or statement) can throw a NullPointerException when foo is null.

  • foo.new SomeInnerClass() throws a NullPointerException when foo is null.

  • Method references of the form name1::name2 or primaryExpression::name throws a NullPointerException when evaluated when name1 or primaryExpression evaluates to null.

    a note from the JLS here says that, someInstance.someStaticMethod() doesn't throw an NPE, because someStaticMethod is static, but someInstance::someStaticMethod still throw an NPE!

* Note that the JLS probably also says a lot about NPEs indirectly.

Aguirre answered 20/10, 2008 at 13:18 Comment(24)
"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.Aristocrat
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.Kilovoltampere
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..Leipzig
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.Bumbling
Another small addition is to try to use Optional return types if it's not mandatory for our logic to not return values, if we want to force a check in the caller.Astrodome
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?)Determine
Downvoted because it's not true that Java sets a variable to its default value if you declare it within a method. It only does this with instance variables. If you declare a variable within a method without assigning it a value, and then try to use it, you will get the variable may not be initialized compiler error.Amalbergas
@Aristocrat The example doesn't make sense to begin with, since Integer is an immutable type. You can't "do something to num".Volcano
A pointer is a primitive value, of a primitive type. It's the pointee that isn't.Tactless
Another common root cause of NPE is to create an object from a query and call properties on that object without checking if it is empty. Eg: Document document = repo.getDocumentSetByFilter(filter).get(0).getFirstDocument(); Here an NPE can be fixed by performing an empty check after .get(0) and before .getFirstDocument();Dysarthria
Also, I think it's important to clarify that NullPointerException is an unchecked exception as opposed to a checked exception. This is a good starting place to start learning the difference between checked and unchecked exceptions.Equites
good explanation but sometimes it's not a good practice to handle this exception by if and else, consider a service that you're providing: it would be better if you let the consumer know that the request causes a null pointer exception. Sometimes handling these events by throwing a proper exception would be more useful.Comprehensible
@Vincent Maybe you could add that a NullPointerException is sometimes thrown when auto-unboxing takes place: Boolean b; and then if (b) { ... }. It sometimes confuses newbies.Gorey
what about using Null Object Design Pattern ? when it is recommended ?Narrow
General advice to NPEs: On public/package/protected methods, do always validate any incoming parameter on null and include a developer-friendly message: if (null == someParameter) { throw new NullPointerException("someParameter is null");` If someParameter is a DAO, and I know it **must** be fully persisted when handled over, I also check it's primary key below above general check: if (someParameter.getSomeId() == null) { throw new NullPointerException("someParameter.someId is null");`.Net
And to make sure, the id is never below one: if (someParameter.getSomeId() < 1) { throw new IllegalArgumentException("someParameter.someId="+someParameter.getSomeId()+" is invalid"); This way, I make sure that my public/package/protected (not private, as this makes unit-testing much harder) are properly invoked.Net
NullPointerException is thrown when an application attempts to use an object reference that has the null value. These include: Calling an instance method on the object referred by a null reference. Accessing or modifying an instance field of the object referred by a null reference. If the reference type is an array type, taking the length of a null reference. If the reference type is an array type, accessing or modifying the slots of a null reference. If the reference type is a subtype of Throwable, throwing a null reference.Abreu
When you access some property of an object on null reference, then NullPointerException is thrown.Cure
One interesting aspect to "prevent" NullPointerExceptions from happening since Java 8 is the Optional<T> class. If misused it does not prevent it but if used correctly it can help enourmously by enforcing checks on places where null may be passed by methods. The idea behind it is that it wraps around the actual object that you are passing and provides an isPresent method to check whether a vaiable is present or not. Although this could be done by an != null check, the advantage is the clarity that if you see that an Optional is returned by a method, you instantly know it can be null.Kiangsu
Downvoted because it is factually incorrect that between declaring the local variable num and assigning an Integer reference to it, its value would be null. In fact, its value is unassigned, and trying to use it is a compile-time error. Instance variables get initialized to null when an object is created, but the above example seems to be about a local variable.Ledger
If you are using jdk8 then would suggest ofNullable API. opt = Optional.ofNullable(null); assertFalse(opt.isPresent());Uprise
Surprisingly nobody mentioned static code analysis here. IntelliJ, Eclipse and find bugs do help identify these during development. Steps r here: fromdev.com/2018/02/good-bye-nullpointerexception-in-java.htmlBrooklime
You should also never use the Integer(int) constructor. I believe it's even deprecated in newer Java versions. Use Integer.valueOf(int) instead.Gorey
Java 8 has introduced "Optional" class to handle null .The purpose of the class is to provide a type-level solution for representing "Optional" values instead of null references. As an example an argument passed to "of" method of "Optional" will throw a NullPointerException. Nevertheless the "ofNullable" method doesn't throw an exception but rather returns an empty Optional object.Dicta
B
967

NullPointerExceptions 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.)

Bun answered 20/10, 2008 at 13:18 Comment(11)
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.Mechanism
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?Rieger
References don't 'point to null'. They are null, or point to an object.Catalinacatalo
@EJP I think your points are valid, so I've updated the answer to be clearer and to avoid saying 'points to null' where it did.Vanadium
@StevePowell I indicated a long time ago that I didn't want my answer to change. Please respect the intent of the original author.Bun
Sorry, I was "improving the answer" as requested in the top of this stackoverflow item (This question's answers are a collaborative effort: if you see something that can be improved, just edit the answer to improve it!) I disagree that your version is better, IMO @EJB has valid points; but you are quite welcome to keep your answer intact, confusing though it is.Vanadium
I'm not sure if it's the same in Java, but in C, NULL is the pointer to memory location 0, which is defined by the standard as an invalid memory location (in the sense that you can't read/write the value there). So, if it's the same in Java, more accurate may be "pointing to a specific, predetermined invalid memory spot that means 'has no value'".Fitly
@QPaysTaxes NULL in C is nearly always a macro for the literal zero (o). If interpreted as a pointer this points to the memory address zero, which is normally not addressable, and certainly not updatable. It is not the same in Java, where null is a keyword, and denotes a (typeless) value which is assignable to object variables or fields. It does not "point to null", it isn't a pointer at all.Vanadium
I find the example misleading. If hashCode() had been an extension method, the call could well have passed through. Better to show examples where you try to access a field.Chemaram
@MadsBoyd-Madsen This is Java code written in 2008. There's nothing misleading about it.Bun
@MadsBoyd-Madsen No worries. The year this was published isn't being displayed as it normally would, since it's a community wiki post that's been edited many times.Bun
T
749

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:

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).

Tacho answered 20/10, 2008 at 13:18 Comment(3)
@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.Tacho
@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.Tacho
i suggest also static analysis tools, like FINDBUGS en.m.wikipedia.org/wiki/FindBugsUntune
O
553

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 labeled "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, or instanceof.

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 the Test 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.

See also: What is a stack trace, and how can I use it to debug my application errors?

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 is null then bar[pos] will throw an NPE.
  • If the value of bar[pos] is null then calling length() 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 this 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.

What about on Android?

On Android, tracking down the immediate cause of an NPE is a bit simpler. The exception message will typically tell you the (compile time) type of the null reference you are using and the method you were attempting to call when the NPE was thrown. This simplifies the process of pinpointing the immediate cause.

But on the flipside, Android has some common platform-specific causes for NPEs. A very common is when getViewById unexpectedly returns a null. My advice would be to search for Q&As about the cause of the unexpected null return value.

Ostracon answered 20/10, 2008 at 13:18 Comment(0)
S
455

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
Spile answered 20/10, 2008 at 13:18 Comment(1)
If we give System.out.println(a.length()); // NullPointerException will be thrown, to skip this we can handle with try catch block. thank youOrphism
G
381

A null pointer exception is thrown when an application attempts to use null in a case where an object is required. These include:

  1. Calling the instance method of a null object.
  2. Accessing or modifying the field of a null object.
  3. Taking the length of null as if it were an array.
  4. Accessing or modifying the slots of null as if it were an array.
  5. 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

Gavrielle answered 20/10, 2008 at 13:18 Comment(3)
Keep it simple, I like this answer, add this if you consider correct - Access to uninitialized attribute of an objectBacteriostat
@Bacteriostat - simply accessing an initialized attribute does not cause an NPE. It is what you >>do<< with the uninitialized attribute value that causes the NPE.Ostracon
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.Ostracon
C
358

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.

Crossstitch answered 20/10, 2008 at 13:18 Comment(1)
"A NULL pointer is one that points to nowhere" I disagree. Null pointers don't point to nowhere, they point to null values.Magus
P
347

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 NullPointerExceptions 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:

  1. Use the final modifier to enforce good initialization.
  2. Avoid returning null in methods, for example returning empty collections when applicable.
  3. Use annotations @NotNull and @Nullable
  4. Fail fast and use asserts to avoid propagation of null objects through the whole application when they shouldn't be null.
  5. Use equals with a known object first: if("knownObject".equals(unknownObject)
  6. Prefer valueOf() over toString().
  7. Use null safe StringUtils methods StringUtils.isEmpty(null).
  8. Use Java 8 Optional as return value in methods, Optional class provide a solution for representing optional values instead of null references.
Poteet answered 20/10, 2008 at 13:18 Comment(11)
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 }Londoner
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.Threat
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.Moot
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.Poteet
Read this ... before you accept these "best practices" as truth: satisfice.com/blog/archives/27Ostracon
A NULL pointer is one that points to nowhere or null reference. 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. public void doSomething(Object obj){ //check for null if(obj != null){ //do something } else { //do something else } }Cleareyed
I also use final on parameters as the instance (where it points to) should mostly (99.999% of all parameters) not be changed. Sure you can still change values.Net
Marking a (temporary) fieldfinal means that you can't reassign it. How can this produce/avoid a NullPointerExceptions at all ? --> conclusion: it is completely off topic.Thrasher
You should write like Data_Type.valueOf(Some_Variable/view)Diacritic
Not a fan of the annotations (#3). I think human error just overcomplicates things here.Blacking
A very interesting checker developed by fb: engineering.fb.com/2022/11/22/developer-tools/…Poteet
S
340

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 student;

    public School() {
        try {
            student.getId();
        }
        catch(Exception e) {
            System.out.println("Null pointer exception");
        }
    }
}

Because you are using student, but you forgot to initialize it like in the correct code shown below:

public class School {

    Student student;

    public School() {
        try {
            student = new Student();
            student.setId(12);
            student.getId();
        }
        catch(Exception e) {
            System.out.println("Null pointer exception");
        }
    }
}
Surgeonfish answered 20/10, 2008 at 13:18 Comment(2)
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?Iow
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.Tottering
W
338

In Java, everything (excluding primitive types) is in the form of a class.

If you want to use any object then you have two phases:

  1. Declare
  2. Initialization

Example:

  • Declaration: Object object;
  • Initialization: object = new Object();

Same for the array concept:

  • Declaration: Item item[] = new Item[5];
  • Initialization: item[0] = new Item();

If you are not giving the initialization section then the NullPointerException arise.

Wayzgoose answered 20/10, 2008 at 13:18 Comment(2)
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(); }Osteomalacia
Or use exception capture: such as: try { yourRef.someMethod(); } catch (NullPointerException e) { // TODO }Osteomalacia
S
330

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.

Sniperscope answered 20/10, 2008 at 13:18 Comment(0)
O
302

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));
}
Ode answered 20/10, 2008 at 13:18 Comment(4)
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.Gaberdine
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:Orang
@Orang 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.Ode
@Shomu: At what point do I even suggest that it should be caught?Ode

© 2022 - 2024 — McMap. All rights reserved.