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?
method greet()
is static, thus it does not need an enclosing instance of Null
. Actually, you can [and should] invoke it as: Null.greet();
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With