Why doesn't this raise a NullPointerException?

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 quit NullPointerException.

Why is this happening?

+5
source share
2 answers

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

If you remove the modifier static, you will getnpe

+6
source

the method greet()is static, so it does not require an attached instance Null. In fact, you can [and should] call it like:Null.greet();

+11
source

All Articles