Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this method call on a null object run without a NullPointerException? [duplicate]

Tags:

java

What is the reason for the output? I know it prints Hello World but don’t know why as it should give NullPointerException.

public class Null
{
    public static void greet()
    {
        System.out.println("Hello World");

    }
    public static void main(String[] args)
    {
        ((Null)null).greet();
    }
}
like image 253
aryan Avatar asked Aug 25 '19 04:08

aryan


People also ask

What is the reason for NullPointerException?

What Causes NullPointerException. The NullPointerException occurs due to a situation in application code where an uninitialized object is attempted to be accessed or modified. Essentially, this means the object reference does not point anywhere and has a null value.

How do I fix NullPointerException?

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 variable is null before dereferencing it.

Which exception is thrown when an instance method of a null object gets called access or modifies the field of a null object?

NullPointerException is thrown when program attempts to use an object reference that has the null value. These can be: Invoking a method from a null object. Accessing or modifying a null object's field.

Which exception is thrown when an instance method of a null object?

NullPointerException is thrown when an application attempts to use an object reference that has the null value. These include: Calling an instance method on the object referred by a null reference.


2 Answers

This is because greet()is a static method. So

((Null)null).greet();

is equivalent to,

Null.greet()
like image 181
Vikas Yadav Avatar answered Sep 17 '22 18:09

Vikas Yadav


Since greet is a static method, a class instance is not needed (and not used...) to invoke it.

The ((Null)null) expression doesn't dereference null, it simply serves as a type definition used to access the static method.

like image 34
Amit Avatar answered Sep 21 '22 18:09

Amit