Hi ,
As far as I understand most of the operations on null results in RE:NullPointerException.
Then why not this one .
class A {
static void go(){ }
public static void main(String s[]) {
A a = null;
a.go();
}
}
The NullPointerException gets thrown when you try to access something on an object, when there is actually no object.
Consider this:
class A{ public void go(); public static void main(String args[]) { A a = null; a.go(); } }
Note that the go() method is a non-static, which means it needs to be accessed on an object of A. However, you can see that the reference variable a does NOT hold an object - it's simply null.
So when we says a.go(); we are asking the JVM to call go() on the object the variable a holds. As it turns out, a does not hold an object, the JVM can't do anything other than throwing a NullPointerException
Now, if the go() method was static as in your example, that would be a different case. In the case of static methods (and variables), we do NOT need an object of the surrounding class. Instead, we are accessing the variable on the class itself - which is the whole point of making something static. In other words, if go() was static, you could simply call the method on the class A just like this:
A.go();
You see - we didn't even need to create an object of the class A. Even if we do create an object of the class A, and try to call the go() method on that object, it actually calls right on the class A behind the scene, if go() was static.
A a = new A(); a.go(); A.go();
In the above code fragment, the line-2 and line-3 are equivalent. Why? Because go() is static, it does not work on an object of A. This is the same reason why a.go() does not throw NullPointerException even if a holds null.
A a = null; a.go();
It may 'look' like we are trying to call the go() method on null, but actually we are calling it on the class A because go() is static.
Does that make it a bit more clearer for you now?