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());
 }
}
4
  • 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. Commented May 4, 2017 at 17:34
  • stackoverflow.com/questions/24800309/… is not an exact duplicate, but it has a lot of good answers for your question. Commented May 4, 2017 at 17:34
  • @Lalaland: Actually, that is a suitable duplicate. Good eyes on finding it. Commented May 4, 2017 at 17:35
  • Have you considered reading the documentation? Read the Fine Manual! docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#d5e24541 Commented May 4, 2017 at 18:42

1 Answer 1

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());
 }
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.