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.

🌐
GeeksforGeeks
geeksforgeeks.org › java › null-pointer-exception-in-java
Null Pointer Exception in Java - GeeksforGeeks
5 days ago - The best way to avoid NullPointerException is to identify where a reference can be null and handle that case before performing an operation on it.
Top answer
1 of 2
4227

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.

2 of 2
972

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

Discussions

Why Null Pointer are so bad? (Java)

You don't get a NullPointerException just because some method returned null. You get a NullPointerException when you try to use null in a way that doesn't make sense. So Java melts down for the same reason that it melts down if you cast a double to an array of strings; the language doesn't know what you were trying to do, so it might do something horribly wrong if it keeps going.

More on reddit.com
🌐 r/learnprogramming
11
1
February 18, 2017
[Java] Can someone nullpointerexception to me in layman's terms?
What I understand so far is that basically, null is a variable that exists but does not hold a value. Hmm, not exactly. null as a concept represents the absence of a value. null is materially different than 0, or an empty string (""); those are values. null means "no value". Now, to really understand what a NullPointerException is, you have to understand what a reference is. When you say this: String myString = "Hello World"; You are creating a block of memory somewhere in your system's memory, and storing the data "Hello World" inside it. Then, it's taking the memory address of that block of memory and storing it inside a variable called myString. When you use myString, Java is dereferencing that memory address and using the value stored there. When you pass the variable to a function, you aren't copying the string, just the address of the string. This address is considered a "pointer" to the real value. But, what if you wanted to have a string variable but you don't want it set to anything? Or just haven't set it to anything? String myString; What value does this hold? Well...it doesn't. It is null. What null actually maps to is a memory address of 0. i.e. not a real address; it lets the system know that "this is not a value". When you create a string array, each cell of the array is a block that can hold one of those addresses. But by default each cell is unset; therefore null. When you call this code: words[0].toUpperCase() You say "get me the string in the very first cell of the words array. Then dereference it, and call toUpperCase() on it." But since it doesn't actually point to a real block of memory, it can't call toUpperCase() on it because "it" doesn't exist. So it crashes. Hope that helps. More on reddit.com
🌐 r/learnprogramming
11
1
March 5, 2020
How to fix NullPointerException in for loop?
If a null value is possible for bookTitle then you will get a nullPointer because it can't evaluate the statement. Boolean values (which is what the if is checking) can only exist in 1 or 0. A null value has neither so it can't be evaluated. You could wrap the if statement in another if statement: if(bookshelf[i].bookTitle != null) { //your if statement here here } This way, if the title is null, it will just skip it and move to the next bookshelf. (Or, which would be more ideal...don't allow bookTitle to be null when bookshelf is made. Make it an empty string, just not Null.) More on reddit.com
🌐 r/learnjava
5
1
April 17, 2019
What are your strategies to prevent nil pointers errors in your code base?
So prevention wise, my rule is if it's data, it shouldn't need pointers, unless they are big. To find bugs, fuzzing the heck out of the code. More on reddit.com
🌐 r/golang
72
31
June 24, 2022
🌐
Pluralsight
pluralsight.com › blog › software development
How to handle (and avoid) NullPointerExceptions in Java | Pluralsight
The practice of unit testing is also generally important and can come to your aid when preventing null pointers. For example, consider a test for Widget, our class from earlier, that ensures it is robust against null usage:
🌐
Medium
medium.com › developers-journal › how-to-handle-null-pointer-exception-in-java-776ab2e0d8f5
How to Handle Null Pointer Exception in Java | by DJ | Developers Journal | Medium
January 27, 2022 - Instead, consider using the static String.valueOf method, which does not throw any exceptions and prints "null", in case the function’s argument equals to null. The ternary operator can be very useful and can help us avoid the NullPointerException. The operator has the form: ... First, the boolean expression is evaluated. If the expression is true then, the value1 is returned, otherwise, the value2 is returned. We can use the ternary operator for handling null pointers as follows:
🌐
Medium
medium.com › @kiranbjm › what-is-a-null-pointer-exception-de351fb907e7
What is a Null Pointer Exception? | by Kiran Benny Joseph | Medium
October 26, 2024 - Check for Nulls: Use conditional ... values to prevent null references. Exception Handling: Use try-catch blocks (where applicable) to manage NPEs gracefully....
Find elsewhere
🌐
freeCodeCamp
freecodecamp.org › news › how-to-handle-nullpointerexception-in-java
How to Handle NullPointerException in Java
July 13, 2020 - The idea is that, when you expect a value to be null, its better to put a null check on that variable.
🌐
Udemy
blog.udemy.com › home › it & development › software development › understanding null pointer exception
Understanding Null Pointer Exception - Udemy Blog
April 14, 2026 - A null pointer exception crashes your program when code tries to use a reference variable pointing to null. This article covers how it occurs in Java and C#, and two ways to handle it: null checks and try-catch blocks. You'll know exactly why it happens and how to fix it.
🌐
Rollbar
rollbar.com › home › how to catch and fix nullpointerexception in java
How to Catch and Fix NullPointerException in Java
June 30, 2026 - NullPointerException is the most frequently thrown exception in Java applications, accounting for countless crashes. It occurs when your code tries to use a variable that doesn't point to any object and instead refers to nothing (null). Think of it like trying to open a door that doesn't exist. You reach for the handle, but there's nothing there—just empty space.
🌐
Medium
supakon-k.medium.com › 4-ways-to-handle-null-objects-in-java-7e2596c235d
4 ways to handle NullPointerException in Java | by Supakon_k | Medium
August 5, 2022 - When assigning value to the object and checking exceptions simultaneously, it is easy to use. ... String result = list.stream() .filter(value -> value.contains("A")) .findFirst() .orElseThrow(() -> new NullPointerException("data is null"));
🌐
How to do in Java
howtodoinjava.com › home › exception handling › java nullpointerexception
Handling Java NullPointerException and Best Practices
October 1, 2022 - Java NullPointerException (NPE) is an unchecked exception and extends RuntimeException. NullPointerException doesn’t force us to use a try-catch block to handle it. NullPointerException has been very much a nightmare for most Java developers. It usually pop up when we least expect them.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › lang › NullPointerException.html
NullPointerException (Java Platform SE 8 )
July 21, 2026 - Applications should throw instances of this class to indicate other illegal uses of the null object. NullPointerException objects may be constructed by the virtual machine as if suppression were disabled and/or the stack trace was not writable · Submit a bug or feature For further API reference ...
🌐
Sentry
sentry.io › sentry answers › java › avoiding `nullpointerexception` in java
Avoiding `NullPointerException` in Java | Sentry
July 12, 2022 - The Java API documentation on NullPointerException lists a couple of scenarios where this exception could be invoked: Calling the instance method of a null object. Accessing or modifying the field of a null object.
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-lang-nullpointerexception
Java NullPointerException - Detect, Fix, and Best Practices | DigitalOcean
August 3, 2022 - Technical tutorials, Q&A, events — This is an inclusive place where developers can find or lend support and discover new ways to contribute to the community.
🌐
Scaler
scaler.com › home › topics › null pointer exception in java
Null Pointer Exception in Java - Scaler Topics
March 20, 2024 - Null pointer exception occurs when the program uses the reference of the object set to null. We can handle null pointer exceptions by making some changes in programs, such as invoking methods directly with literals instead of null objects.
🌐
Snyk
snyk.io › blog › how-to-prevent-nullpointerexceptions-in-java
How to prevent NullPointerExceptions in Java | Snyk
September 21, 2023 - This approach is important for preventing potential NullPointerExceptions by checking for null values at runtime and throwing an exception if null values are encountered. When using interfaces, provide default methods to handle potential null objects, thus avoiding NullPointerExceptions:
🌐
DEV Community
dev.to › sharmaprash › what-is-a-nullpointerexception-and-how-do-i-fix-it-1j3i
What is a NullPointerException, and how do I fix it? - DEV Community
November 21, 2024 - Wrap potentially null values in java.util.Optional, which provides methods like isPresent() or ifPresent() to safely handle null. Optional<String> optionalStr = Optional.ofNullable(str); optionalStr.ifPresent(s -> System.out.println(s.length())); Use annotations like @Nullable and @NonNull to signal which variables or parameters can be null and which cannot. IDEs like IntelliJ IDEA or Eclipse can warn you at compile-time if you misuse these. Use an IDE's debugger to inspect the state of variables at runtime and identify the null value causing the exception.
🌐
Codegive
codegive.com › blog › null_pointer_exception.php
Master Null Pointer Exception (2026): Debug Like a Pro & Eliminate Runtime Crashes Forever
A: To fix a null pointer exception, you need to identify the exact line of code where a null object reference is being used. Then, ensure that the object is properly initialized or assigned a non-null value before it's dereferenced. This often involves adding null checks (if (object != null)) ...
🌐
Quora
quora.com › How-do-you-handle-a-null-pointer-exception-in-Java-using-try-catch
How to handle a null pointer exception in Java using try catch - Quora
Answer (1 of 3): Ideally all your null pointer exceptions happen during development and testing, never in production. So generally your program shouldn’t try to handle [code ]NullPointerException[/code]. Instead, you handle it by correcting the program so that any null pointers that occur ...