public class JavaPuzzler {
public static void main(String[] args) {
JavaPuzzler javaPuzzler = null;
System.out.println(javaPuzzler.get());
}
private static String get(){
return "i am a java puzzler";
}
}
You might think that it should throw NullPointerException because the main method invokes get() method on local variable which is initialized to null, and you can’t invoke a method on null.
But if you run this program, you will see that it prints “i am a java puzzler”.
Can anybody give me the answer. Thanks in advance.
If you call a static method on an object with a null reference, you won't get an exception and the code will run. This is admittedly very misleading when reading someone else's code, and it is best practice to always use the class name when calling a static method.
Yes, main method have a signature as any other method. And array in java are nullable. Check what recursive functions are.
You have to call with an object. If the method is static the object can be the class.
In Java, a null value can be assigned to an object reference of any type to indicate that it points to nothing. The compiler assigns null to any uninitialized static and instance members of reference type. In the absence of a constructor, the getArticles() and getName() methods will return a null reference.
In your code sample, get()
is a static member that belongs to the class, not to an instance. You do not need an instance in order to invoke the method.
public static String get() // belongs globally to class, no instance required
public String get() // belongs to instance
It's because the method is static and though you reference an instance, the instance isn't necessary. The Java Language Specification explains why in section 8.4.3.2:
A method that is declared static is called a class method. A class method is always invoked without reference to a particular object.
This means that it does not matter if javaPuzzler
instance is null - the method "belongs" to the class, not an instance.
The get
method is static, which means that the actual reference in javaPuzzler
is ignored in that call, only the variable's type is used.
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