Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this not cause a NullPointerException?

Tags:

java

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

    public static void main(String[] args) {
        ((Null) null).greet();
    }
}

program output: Hello world!.
I thought it would throw a NullPointerException.

Why is it happenning?

like image 314
Saurabh Kumar Avatar asked Jan 19 '12 20:01

Saurabh Kumar


2 Answers

method greet() is static, thus it does not need an enclosing instance of Null. Actually, you can [and should] invoke it as: Null.greet();

like image 80
amit Avatar answered Oct 08 '22 15:10

amit


The reason is that greet() is a static method. References to static methods via variables do not result in dereferencing the pointer. The compiler should have warned you about this.

If you remove the static modifier then you will get the npe

like image 40
Miserable Variable Avatar answered Oct 08 '22 17:10

Miserable Variable