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:

Use with AIint 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:

Use with AIInteger 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:

Use with AIpublic 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:

Use with AIdoSomething(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:

Use with AI// 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:

Use with AI/**
  * @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:
Use with AIclass 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
September 8, 2026 - Since a null reference does not point to any actual object, calling its methods or accessing its fields causes the Java Virtual Machine (JVM) to throw a NullPointerException. Can occur while invoking methods, accessing fields, or using arrays. Helps identify improper object initialization or missing assignments. Can be prevented using null checks or Objects.requireNonNull().
Top answer
1 of 12
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:

Use with AIint 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:

Use with AIInteger 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:

Use with AIpublic 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:

Use with AIdoSomething(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:

Use with AI// 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:

Use with AI/**
  * @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:
Use with AIclass 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 12
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:

Use with AIpublic 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

[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
java.lang.nullpointerexception: group
That error is extremely common in software from all sorta of causes so more details will be needed to narrow it down. Any additional information contained with the error would be needed. Minecraft may not display it on screen, but you can try enabling the message window (or whatever it's called) in the launcher. The error might show up there with more details when it happens. You might try to reboot both your PCs since it sounds like it was working yesterday. Other things to try: Make sure the Minecraft launcher on both PCs is set to the same Minecraft version. Make sure he can still run singleplayer and it's just a problem with multiplayer. This can help narrow down the issue at least. Run the latest video driver installer on his PC. Install the latest Java version on both your PCs (not sure if this matters). The technical reason for a nullpointerexception is that the developer forgot to account for some condition, usually a rare one, that isn't satisfied, so the game can't continue running. Sometimes the game couldn't run anyway so the developer doesn't bother trying to handle the condition, sometimes the developer forgets to provide a more useful error message for the condition, More on reddit.com
🌐 r/Minecraft
10
4
October 29, 2018
Eliminating Null Pointer Exceptions
IMO, the existence of null pointers in a memory safe language is contrary to its purpose. Null pointers are memory safety. They prevent you from doing the memory unsafe thing of referencing unintialized memory. More on reddit.com
🌐 r/java
91
0
June 24, 2024
Null Pointer Exception why??
Ok, just looked at the insertSort... if head isn't null and your data being inserted should be at the head you.... throw away the list by moving the head forward one then just assigning it to the new node? Ok, so the first head = head.next is supposed to be maybe next = head? You might want to read through your methods to see if what they do makes sense. Or maybe I'm having a bad day. More on reddit.com
🌐 r/javahelp
6
0
January 26, 2022
People also ask

What does the Null Pointer Exception program demonstrate?
It shows how to implement null pointer exception in Java with a complete runnable example and expected console output.
🌐
java-programs.thiyagaraaj.com
java-programs.thiyagaraaj.com › home › oops › exception handling programs › null pointer exception example in java
Null Pointer Exception Example in Java - Java Programs
How do I run this Java program?
Save the code in a `.java` file matching the public class name, compile with `javac`, then run with `java ClassName`.
🌐
java-programs.thiyagaraaj.com
java-programs.thiyagaraaj.com › home › oops › exception handling programs › null pointer exception example in java
Null Pointer Exception Example in Java - Java Programs
🌐
Tutorialspoint
tutorialspoint.com › java › java_nullpointerexception.htm
Java - Null Pointer Exception
And with multiple nesting level, it becomes more difficult to check which field being null is causing the issue. Java 14 catered to this need. It provided an option to return a more helpful message like below in such case: Exception in thread "main" java.lang.NullPointerException: Cannot invoke "com.tutorialspoint.Department.getName()" because the return value of "com.tutorialspoint.Employee.getDept()" is null at com.tutorialspoint.Tester.main(Tester.java:10)
🌐
Scaler
scaler.com › home › topics › null pointer exception in java
Null Pointer Exception in Java - Scaler Topics
March 20, 2024 - We can avoid the null pointer exception in the above code by invoking the equals method with a literal instead of the myString variable on line 8. ... We can avoid the null pointer exception in Java by checking whether the arguments are null.
🌐
Sentry
sentry.io › sentry answers › java › what is a nullpointerexception, and how do i fix it?
Java NullPointerException: Common Causes and How to Fix | Sentry
September 21, 2026 - For example, in the code below we call .length() on myString, which would usually return the length of the string. In this case, the string doesn’t exist (we set it to null), and so this throws a NullPointerException.
🌐
Java Programs
java-programs.thiyagaraaj.com › home › oops › exception handling programs › null pointer exception example in java
Null Pointer Exception Example in Java - Java Programs
May 29, 2026 - It shows how to implement null pointer exception in Java with a complete runnable example and expected console output.
Find elsewhere
🌐
Sentry
sentry.io › sentry answers › java › avoiding `nullpointerexception` in java
Avoid NullPointerException in Java with Null Checks | Sentry
October 1, 2026 - Exception in thread "main" java.lang.NullPointerException at NullPointerExample.printFirstElement(NullPointerExample.java:6) at NullPointerExample.main(NullPointerExample.java:11)
🌐
Edureka
edureka.co › blog › null-pointer-exception-in-java
Null Pointer Exception in Java: Implementation and Examples | Edureka
June 17, 2021 - In order to avoid the Null Pointer Exception in Java, we must make sure that all the objects are initialized properly before you use them. When a reference variable is declared, we must verify that an object is not null and also Before we request methods or fields from objects. The following are some problems with its corresponding solutions to overcome that problem.
🌐
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.
🌐
javaspring
javaspring.net › blog › null-pointer-exception-java
Understanding and Handling Null Pointer Exceptions in Java — javaspring.net
When a NullPointerException is thrown, Java provides a stack trace that shows the sequence of method calls that led to the exception. The stack trace usually indicates the line number where the exception occurred, which can help you pinpoint the source of the problem. For example, if you run the NullPointerExample code above, the stack trace might look like this:
🌐
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 - It’s one of the most common runtime exceptions in Java and is typically caused by attempting to: Call a method on a null object.
🌐
How to do in Java
howtodoinjava.com › home › exception handling › java nullpointerexception: how to fix and avoid it
Java NullPointerException: How to Fix and Avoid It
October 10, 2026 - A Java NullPointerException (NPE) is the exception the JVM throws when code uses a null reference as if it pointed to an object. For example, the code calls name.length() while name is null.
🌐
Medium
medium.com › @bigdataetlcom › what-is-a-nullpointerexception-in-java-lets-understand-and-learn-how-to-avoid-it-33fe3a636519
What Is A NullPointerException in Java? Let’s Understand And Learn How To Avoid It! | by BigData-ETL | Medium
September 7, 2022 - When you try to use a reference that points to no location in memory (java null) as if it were addressing an object, you get a NullPointerException. NullPointerException is thrown when a method is called on a null reference or when a field of ...
🌐
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. And if the value does turn out to be null, take an alternative action. This is applicable not only to strings, but to any other object in Java.
🌐
WeblineIndia
weblineindia.com › home › blog › how to fix nullpointerexception in java? (13 ways with examples)
How to Fix NullPointerException in Java? (13 ways with examples)
June 30, 2026 - The first step in fixing a NullPointerException is to look at the stack trace that is printed out when the exception occurs. The stack trace tells you exactly where the exception occurred, giving you a line number and a reference to the method or code block that caused it. For example, Exception in thread "main" java.lang.NullPointerException at com.example.MyClass.myMethod(MyClass.java:10)
🌐
Java Code Geeks
examples.javacodegeeks.com › home › java development › java basics › exceptions
java.lang.NullPointerException Example
July 6, 2022 - In this post, we feature a comprehensive example of java.lang.NullPointerException – Java Null Pointer Exception. In Java, a special null value can be assigned to an object’s reference and denotes that the object is currently pointing to an unknown piece of data.
🌐
Blogger
javarevisited.blogspot.com › 2012 › 06 › common-cause-of-javalangnullpointerexce.html
How to deal with NullPointerException in Java with Examples - java.lang.NullPointerException Guide
Though I agree that, a method should not return null, if possible it return a default value e.g. an Empty object like empty String, empty collection or Java 8's Optional value, which indicate they value can be absent and ensure that caller of method code for the case when value is not present in Optional. Apart from that you can use the tips mentioned in the linked article avoid NullPointerException in Java ... Kislaya Pant said... I am getting runtime error (Null Pointer exception) while using .equals method with string array..
🌐
Tutorialspoint
tutorialspoint.com › java › lang › java_null_pointer_exception.htm
Java - NullPointerException
public class NullPointerExceptionExample { public static void main(String[] args) { String str = null; System.out.println(str.length()); } } ... Exception in thread "main" java.lang.NullPointerException at NullPointerExceptionExample.main(N...
🌐
Pluralsight
pluralsight.com › blog › software development
How to handle (and avoid) NullPointerExceptions in Java | Pluralsight
Java throws a NullPointerException when an application attempts to use a field or method on a null reference. For example, Java will throw a NullPointerException in the following code:
🌐
Intellipaat
intellipaat.com › home › blog › null pointer exception in java
Null Pointer Exception in Java - Intellipaat
August 5, 2026 - The NullPointerException is an unchecked exception in Java that occurs during runtime when we try to call a method or access a variable on a null reference. While working with Java, we might get a runtime error while running a Program.