๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ null-pointer-exception-in-java
Null Pointer Exception in Java - GeeksforGeeks
September 8, 2026 - A NullPointerException (NPE) is a runtime exception in Java that occurs when a program tries to access or use an object reference that has the value null. 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.
๐ŸŒ
Tutorialspoint
tutorialspoint.com โ€บ java โ€บ java_nullpointerexception.htm
Java - Null Pointer Exception
In output we can see the informative null pointer exception raised by the JVM. package com.tutorialspoint; import java.util.List; public class Tester { public static void main(String[] args) { // declare an employee without department Employee emp = new Employee(1,"Robert",null); // get department name of null department will // throw a NullPointerException String dept = emp.getDept().getName(); System.out.println(dept); } } class Employee { int id; String name; Department dept; Employee (int id, String name, Department dept){ this.id = id; this.name = name; this.dept = dept; } public int getI
Discussions

java - What is a NullPointerException, and how do I fix it? - Stack Overflow
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 progra... More on stackoverflow.com
๐ŸŒ stackoverflow.com
[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 do I avoid the NullPointerException in Mockito, jUnit testing?
I think calling mock(YourClass.class) returns a mock which upon calling its methods throws a NPE. This mean you should explicitly use doCallRealMethod(yourMock).when(yourMethod()) if you want the mock's method to behave like it normally would. By calling Mockito.spy(YourClass.class) it will create a mock which by default uses the real methods, if you don't specify otherwise More on reddit.com
๐ŸŒ r/javahelp
5
1
August 16, 2017
Why do I get a NullPointerException when trying to access my methods, but the program runs fine?
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
๐ŸŒ r/javahelp
12
1
November 9, 2023
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
๐ŸŒ
Java Code Geeks
examples.javacodegeeks.com โ€บ home โ€บ java development โ€บ java basics โ€บ exceptions
java.lang.NullPointerException Example
July 6, 2022 - Notice that, when you declare a reference variable, you are really creating a pointer to an object. You must verify that the pointer is not null, before you request the method or a field from the object. Also, if the exception is thrown, use the information residing in the exceptionโ€™s stack trace.
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ null pointer exception in java
Null Pointer Exception in Java - Scaler Topics
March 20, 2024 - Refer to the following coding example to understand the null pointer exception in java. ... In this, we initialized the null value to an object, obj. On the obj object, we performed the toString() operation. Because the value of obj is null, it throws the null pointer exception, as shown in ...
๐ŸŒ
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.
๐ŸŒ
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 - ... String result = list.stream() .filter(value -> value.contains("A")) .findFirst() .orElseThrow(() -> new NullPointerException("data is null")); when we use the stream method to process something, and after the method finishes the message ...
Find elsewhere
๐ŸŒ
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.
๐ŸŒ
Sentry
sentry.io โ€บ sentry answers โ€บ java โ€บ avoiding `nullpointerexception` in java
Avoid NullPointerException in Java with Null Checks | Sentry
October 1, 2026 - Letโ€™s take a look at a concrete example of where a NullPointerException might be thrown. ... class NullPointerExample { private static void printFirstElement(String[] array) { System.out.println(array[0]); } public static void main(String[] args) { String[] myStringArray = null; printFirstElement(myStringArray); } } Executing this code will result in the following stack trace: Exception in thread "main" java.lang.NullPointerException at NullPointerExample.printFirstElement(NullPointerExample.java:6) at NullPointerExample.main(NullPointerExample.java:11)
๐ŸŒ
Javatpoint
javatpoint.com โ€บ null-pointer-exception-in-java
Null Pointer Exception in Java - Javatpoint
Null Pointer Exception in Java with java tutorial, features, history, variables, programs, operators, oops concept, array, string, map, math, methods, examples etc.
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.)

๐ŸŒ
javaspring
javaspring.net โ€บ blog โ€บ null-pointer-exception-java
Understanding and Handling Null Pointer Exceptions in Java โ€” javaspring.net
Use Defensive Programming: When writing methods, assume that the input parameters may be null and handle them appropriately. You can throw an appropriate exception, such as IllegalArgumentException, if a required parameter is null.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ why-can-i-throw-null-in-java-and-why-does-it-upcast-to-a-nullpointerexception
Why can I throw null in Java and why does it upcast to a NullPointerException?
July 2, 2020 - You can also throw a NullPointerException in Java using the throw keyword. public class ExceptionExample { public static void main(String[] args) { System.out.println("Hello"); NullPointerException nullPointer = new NullPointerException(); throw nullPointer; } }
๐ŸŒ
Pluralsight
pluralsight.com โ€บ blog โ€บ software development
How to handle (and avoid) NullPointerExceptions in Java | Pluralsight
Note that Null Object Pattern is a more advanced pattern and should not be used to propagate validation that is more appropriately dealt with at the call site. For example, it would also be reasonable to throw an exception in getCollege:
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ how-to-handle-nullpointerexception-in-java
How to Handle NullPointerException in Java
July 13, 2020 - If any of the arguments given in the function turn out to be null, the function would throw a NullPointerException.
๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ java โ€บ null pointer exception in java
What Is a Null Pointer Exception in Java | Delft Stack
October 12, 2023 - In Java, the default value of any ... have any associate value. When a programmer tries to perform any operation with this reference variable, it throws a null pointer exception due to null conditions....
๐ŸŒ
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.
๐ŸŒ
Blogger
javarevisited.blogspot.com โ€บ 2012 โ€บ 06 โ€บ common-cause-of-javalangnullpointerexce.html
How to deal with NullPointerException in Java with Examples - java.lang.NullPointerException Guide
In Java reference variable points to object created in heap but when you create a reference variable of type object by default its points to "null" and when you try to call any method on null, try to access any variable on null you will get this null pointer exception. No matter by what reason your reference variable is pointing to null be it not initialized or set to null if you perform any operation it will throw Exception in thread main : java.lang.NullPointerException
๐ŸŒ
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 - Notice that, when you declare a reference variable, you are really creating a pointer to an object. You must verify that the pointer is not null, before you request the method or a field from the object. Also, if the exception is thrown, use the information residing in the exceptionโ€™s stack trace.
๐ŸŒ
Java Guides
javaguides.net โ€บ 2023 โ€บ 08 โ€บ how-to-fix-and-avoid-null-pointer.html
How to Fix and Avoid Null Pointer Exception in Java
January 24, 2024 - Since the NullPointerException is a runtime exception, it doesn't need to be caught and handled explicitly in the application code. Uninitialized Objects: Trying to use an object without initializing it first. Default Array Values: Accessing an object array that has not been fully initialized. External APIs: Relying on values from external sources which might return null.