Reputation: 16651
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?
Upvotes: 6
Views: 307
Reputation: 28752
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
Upvotes: 7
Reputation: 178411
method greet()
is static, thus it does not need an enclosing instance of Null
. Actually, you can [and should] invoke it as: Null.greet();
Upvotes: 12