Possible Duplicate:
How come invoking a (static) method on a null reference doesn’t throw NullPointerException?
Can any one explain why the output of the following program is "Called"
public class Test4{
public static void method(){
System.out.println("Called");
}
public static void main(String[] args){
Test4 t4 = null;
t4.method();
}
}
I know we can call static method with class reference , but here I am calling using null reference . please clarify my doubt
In the Byte code
Test4 t4 = null;
t4.method();
will be
Test4 t4 = null;
Test4.method();
Compiler would convert the call with the class name for static methods. refer to this question on SO which i myself have asked it.
It doesn't matter if the instance is null, because you are calling a static method.
Think of it this way.
Every static method is equivalent with a class method whereas a non-static method is equivalent with
an instance method.
Therefor it doesn't matter what value the instance takes as long as you are working with static methods or members.
Static methods can be called via the classname or an instance.
I would try to avoid to call them by an instance (also a lot of tools warn you to do so because of bad practice).