Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How am I able to call a method on a null object?

Tags:

java

core

public class JavaPuzzler {

    public static void main(String[] args) {
    JavaPuzzler javaPuzzler = null;
    System.out.println(javaPuzzler.get());
    }

    private static String get(){
        return "i am a java puzzler";
    }
}

You might think that it should throw NullPointerException because the main method invokes get() method on local variable which is initialized to null, and you can’t invoke a method on null.

But if you run this program, you will see that it prints “i am a java puzzler”.

Can anybody give me the answer. Thanks in advance.

like image 616
Nik88 Avatar asked Dec 21 '11 05:12

Nik88


People also ask

Can you call a method on a null object?

If you call a static method on an object with a null reference, you won't get an exception and the code will run. This is admittedly very misleading when reading someone else's code, and it is best practice to always use the class name when calling a static method.

Can you call Main with null Java?

Yes, main method have a signature as any other method. And array in java are nullable. Check what recursive functions are.

Do you need an object to call a method?

You have to call with an object. If the method is static the object can be the class.

What happens when object is set to null in Java?

In Java, a null value can be assigned to an object reference of any type to indicate that it points to nothing. The compiler assigns null to any uninitialized static and instance members of reference type. In the absence of a constructor, the getArticles() and getName() methods will return a null reference.


3 Answers

In your code sample, get() is a static member that belongs to the class, not to an instance. You do not need an instance in order to invoke the method.

public static String get() // belongs globally to class, no instance required
public String get() // belongs to instance
like image 77
Anthony Pegram Avatar answered Sep 17 '22 16:09

Anthony Pegram


It's because the method is static and though you reference an instance, the instance isn't necessary. The Java Language Specification explains why in section 8.4.3.2:

A method that is declared static is called a class method. A class method is always invoked without reference to a particular object.

This means that it does not matter if javaPuzzler instance is null - the method "belongs" to the class, not an instance.

like image 25
Paul Avatar answered Sep 20 '22 16:09

Paul


The get method is static, which means that the actual reference in javaPuzzler is ignored in that call, only the variable's type is used.

like image 39
ibid Avatar answered Sep 20 '22 16:09

ibid