Access static member by null reference

During one point of the programming I came across with this situation which made me to think about accessing the static member with instance of the declared type.This was never used before due to the genuine warning of Java to access static members in a static way. In particular why does Java allows to access the static (accessible) member with the null reference?

To get more on this consider the following case,

class Test {
  public static Integer NO = 100;

  public static void printHello() {
    System.out.println("HELLO!");
  }

}

public class NullCallStatic {

  public static void main(String[] args) {
     Test test = null;
     test.printHello();
     System.out.println("NUMBER : "+test.NO);
     //above statements will show a WARNING
     //to access static member in a static way
  }

}

You will have the following output:

HELLO!
NUMBER : 100

Consider line number 14 and 15 where we are calling the static method and getting the value of static Integer with a reference which is actually null. Now this surprised me as why didn’t this result in  NullPointerException.

Now let’s know why this had happened,

static refers to the enclosing type and not to the instances

Static members belongs to the enclosing type and does not refer to the individual instance of the type as only one copy of each static member will be created for the type itself and for all the instances of the class the same copy will be used during the execution.

Now when the static member is accessed with instance of declared type, technically the declared type matters to java virtual machine irrespective of the value and it won’t care about the value of instance whether it is null or not null.

So, for accessing the static member with instance the value of instance will actually not used and so that it won’t throw NullPointerException.

Even more it is worth to note that the instance which tries to access the static field is evaluated first by the java virtual machine but the result of evaluation is discarded as it has no use.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s