is it possible?
Object obj=null;
obj.someMethod();
someMethod{/*some code here*/}
You can call a static method on a null pointer. The pointer will naturally be completely ignored in a static method call, but it's still a case when something that (without looking at the class definition) seemingly should cause a NullPointerException runs just fine.
class FooObject {
public static void saySomething() {
System.out.println("Hi there!");
}
}
class Main {
public static void main(String[] args) {
FooObject foo = null;
foo.saySomething();
}
}
But just to make it clear - no, you can't call an instance method with a null pointer. Protecting the programmer against this is one of the really basic protections that set languages like Java apart from "lower level languages" such as C++. It enables the error to be reported at the calling end, instead of it causing an inexplicable segfault/whatnot inside the method itself.
No we can't. it will throw NullPointerException as long as the method is not static. If method is static it will run.
Read this: null : Java Glossary
No. In Java, null is not an object.
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