Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can we call any method on null object?

is it possible?

Object obj=null;

obj.someMethod();

someMethod{/*some code here*/}
like image 915
Anand Avatar asked May 02 '11 08:05

Anand


3 Answers

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.

like image 145
Matti Virkkunen Avatar answered Oct 11 '22 21:10

Matti Virkkunen


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

like image 27
Harry Joy Avatar answered Oct 11 '22 21:10

Harry Joy


No. In Java, null is not an object.

like image 27
Don Roby Avatar answered Oct 11 '22 19:10

Don Roby