Home > Software design >  Why no null pointer exception will be thrown
Why no null pointer exception will be thrown

Time:12-16

Following is the code snippet:

class A {
  static void staticMethod() {
    System.out.println("Static Method");
  }
}


public class App {
  public static void main(String[] args) {
    A a = null;

    a.staticMethod();
  }
}

When A a = null means a is null. Then why a.staticMethod() doesn't throw Null Pointer?

CodePudding user response:

Because staticMethod is static, so the compiler replaces a.staticMethod(); with A.staticMethod();

CodePudding user response:

Quoth the JLS (§15.12.4. Run-Time Evaluation of Method Invocation):

If form is ExpressionName . [TypeArguments] Identifier, then:

If the invocation mode is static, then there is no target reference. The ExpressionName is evaluated, but the result is then discarded.

Otherwise, the target reference is the value denoted by ExpressionName.

And:

If the invocation mode is static, no target reference is needed and overriding is not allowed. Method m of class T is the one to be invoked.

Otherwise, an instance method is to be invoked and there is a target reference. If the target reference is null, a NullPointerException is thrown at this point.

So, a NullPointerException is thrown when the method is not static and the "target reference" is null; but for a static method there is no "target reference", and no null-check is performed.

It would have been possible for the JLS to specify a null-check here, but it does not, so there isn't one. Personally I think it would have made more sense to forbid expressions like a.staticMethod() where a is a variable instead of the class, but for better or worse, the Java language designers chose to allow this.

CodePudding user response:

Because static methods belong to classes, they do not belong to instances of classe

CodePudding user response:

Because of static method, all the static members are resolved at compile time.

  •  Tags:  
  • java
  • Related