1

I surprised with concept why this code works when it has to ideally throw null pointer exception

public class Test {
 public static String foo(){
 System.out.println("Test foo called");
 return "";
 }

 public static void main(String args[]){
 Test obj = null;
 System.out.println(obj.foo());
 }
}
Ashish
  • 1,856
  • 18
  • 30
  • Because a static method doesn't need any instance to be called. It's bound to the class, not to any instance. That said, calling a static method on an instance is bad practice, and even more when the instance is null. – JB Nizet May 04 '17 at 17:34
  • http://stackoverflow.com/questions/24800309/can-we-call-static-method-with-null-object-in-java-if-yes-how is not an exact duplicate, but it has a lot of good answers for your question. –  May 04 '17 at 17:34
  • @Lalaland: Actually, that *is* a suitable duplicate. Good eyes on finding it. – Makoto May 04 '17 at 17:35
  • Have you considered reading the documentation? Read the Fine Manual! http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#d5e24541 – Lew Bloch May 04 '17 at 18:42

1 Answers1

0

When calling a static method, the type reference is relevant not the instance so obj.foo() and Test.foo() get resolved to the same thing.

Best Practice: static members should be accessed statically

While it is possible to access static members from a class instance, it's bad form, and considered by most to be misleading because it implies to the readers of your code that there's an instance of the member per class instance.

https://sonarqube.com/coding_rules#rule_key=squid%3AS2209

Recommend to code as this:

public static void main(String args[]) {
 Test obj = null;
 // ....
 System.out.println(Test.foo());
 }
CodeMonkey
  • 22,825
  • 4
  • 35
  • 75