The parameter that you pass to invoke must be an object on which the method is invoked, unless the method is static. What you did through reflection is equivalent to this:

MyTest obj = null;
obj.testBlah();

Naturally, there's an NPE. To fix this problem, pass an object on which to invoke the method, or make the method static.

Here is one way to make a fix:

public <T> void parse(Class<T> clazz, T obj) throws Exception {
    Method[] methods = clazz.getMethods();
    int pass = 0;
    int fail = 0;

    for (Method method : methods) {
        if (method.isAnnotationPresent(Test.class)) {
            Test test = method.getAnnotation(Test.class);
            Class expected = test.expected();
            try {
                method.invoke(obj);
                pass++;
            } catch (Exception e) {
                if (Exception.class != expected) {
                    e.printStackTrace();
                    fail++;
                } else {
                    pass++;
                }
            }
        }
    }
    System.out.println("Passed:" + pass + "   Fail:" + fail);
}

...

parser.parse(MyTest.class, new MyTest());

Demo on ideone.

Answer from Sergey Kalinichenko on Stack Overflow
🌐
Stack Overflow
stackoverflow.com › questions › 62175950 › nullpointerexception-will-be-thrown-on-method-call
java - NullPointerException will be thrown on method call - Stack Overflow
June 3, 2020 - To avoid the possibility of NullPointerException, I suggest the following implementation for your function: public String getValue(String tag) { if (tag != null) { tag = tag.substring(tag.lastIndexOf('/') + 1).trim(); } return tag; } ... Sign up to request clarification or add additional context in comments. ... they are not equivalent, if tag=" " then returning null or " " are not the same thing 2020-06-03T15:00:37.677Z+00:00 ... If the string is null, you can´t invoke any method on it.
🌐
Sonar Community
community.sonarsource.com › rules and languages › report false-positive / false-negative...
NullPointerException will be thrown when invoking method - Report False-positive / False-negative... - Sonar Community
March 8, 2019 - So I got this issue on our automated SQ check. What I understand is ‘can be null’ - well actually it cannot because of the rules, that prevent nulls to arrive at the point of the check, but I guess that’s what SQ cannot recognize. What I don’t understand is the reasoning step 3 - 4: ...
🌐
How to do in Java
howtodoinjava.com › home › exception handling › java nullpointerexception
Handling Java NullPointerException and Best Practices
October 1, 2022 - Joshua bloch in effective java says that “Arguably, all erroneous method invocations boil down to an illegal argument or illegal state, but other exceptions are standardly used for certain kinds of illegal arguments and states. If a caller passes null in some parameter for which null values are prohibited, convention dictates that NullPointerException be thrown rather than IllegalArgumentException.”
🌐
ADHDecode
adhdecode.com › debugging › java › java-lang-nullpointerexception-invoking-method-on-null
java.lang NullPointerException Invoking Method On Null | ADHDecode
If a field is declared but never ... lifecycle. The error you’re seeing – invoking a method on null – suggests the object exists, but a field within that object, or an object it references, is null. It’s not usually a case of the object itself being uninitiali...
🌐
Squash
squash.io › java-lang-nullpointerexception-how-to
How to Fix the Java NullPointerException - Squash.io
October 14, 2023 - The Nullpointerexception is thrown when you try to access or invoke a method on an object that is not initialized or has a null value. This can happen when you forget to assign a value to an object or when you mistakenly assume that an object ...
🌐
Java Code Geeks
examples.javacodegeeks.com › home › java development › java basics › exceptions
java.lang.NullPointerException - Examples Java Code Geeks - 2026
July 6, 2022 - A java.lang.NullPointerException is thrown when an application is trying to use or access an object whose reference equals to null. The following cases throw Null Pointer exception: Invoking a method from a null object.
🌐
Rollbar
rollbar.com › home › how to catch and fix nullpointerexception in java
How to Catch and Fix NullPointerException in Java
June 30, 2026 - 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.
🌐
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.
Find elsewhere
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:

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

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

🌐
GeeksforGeeks
geeksforgeeks.org › java › null-pointer-exception-in-java
Null Pointer Exception in Java - GeeksforGeeks
6 days ago - 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.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › lang › NullPointerException.html
NullPointerException (Java Platform SE 8 )
July 21, 2026 - 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. NullPointerException objects may be constructed by the virtual machine as if suppression were disabled and/or the stack trace was not writable.
🌐
Sentry
sentry.io › sentry answers › java › avoiding `nullpointerexception` in java
Avoiding `NullPointerException` in Java | Sentry
July 12, 2022 - Executing this code now will yield the following output: The array was null! This is one important technique we can use to avoid tumbling into a NullPointerException during code execution. Some tips for avoiding a NullPointerException include: Perform null checks to ensure that objects are correctly initialized before accessing any of the object’s methods.
🌐
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 - In Java there is default value for every type, when you don’t initialize the instance variables of a class Java compiler initializes them on your be-half with these values. Null is the default value of the object type, you can also manually assign null to objects in a method. ... But, you cannot use an object with null value or (a null value instead of an object) if you do so, a NullPointerException will be thrown.
🌐
Sentry
sentry.io › sentry answers › java › what is a nullpointerexception, and how do i fix it?
What is a NullPointerException, and how do I fix it? | Sentry
In this case, the string doesn’t exist (we set it to null), and so this throws a NullPointerException. public class Main { public static void main(String[] args) { String myString = null; int stringLength = myString.length(); } } You can fix this by ensuring that your object is not null before calling the method.
🌐
Educative
educative.io › answers › how-to-resolve-the-javalangnullpointerexception
How to resolve the java.lang.NullPointerException
In Java, the java.lang.NullPointerException is thrown when a reference variable is accessed (or de-referenced) and is not pointing to any object. This error can be resolved by using a try-catch block or an if-else condition to check if a reference ...
🌐
GitHub
github.com › mockito › mockito › issues › 3237
Method `Only.verify` throws `NullPointerException` · Issue #3237 · mockito/mockito
January 17, 2024 - It triggers the following NullPointerException to be thrown. java.lang.NullPointerException: Cannot invoke "org.mockito.invocation.Invocation.getMock()" because "undesired" is null at org.mockito.internal.exceptions.Reporter.noMoreInteractionsWanted(Reporter.java:555) at org.mockito.intern...
Author: mockito