Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't calling a static variable chained from a static method that returns null throw a NPE?

Tags:

java

null

static

I have the following code

public class Test {
    static String mountain = "Everest";

    static Test favorite() {
        System.out.print("Mount ");
        return null;
    }

    public static void main(String[] args) {
        System.out.println(favorite().mountain);
    }
}

I thought it would raise a NPE but it is giving Mount Everest as output can anyone clarify?

like image 338
MaheshVarma Avatar asked Dec 18 '13 03:12

MaheshVarma


2 Answers

It just so happens that you can access static members on object references. In that case, the member is resolved according to the type of the reference, not its value.

The Java Language Specification says this about field access of static members

If the field is a non-blank final field, then the result is the value of the specified class variable in the class or interface that is the type of the Primary expression.

If the field is not final, or is a blank final and the field access occurs in a constructor, then the result is a variable, namely, the specified class variable in the class that is the type of the Primary expression.

So the Primary, the instance, does not matter.

like image 180
Sotirios Delimanolis Avatar answered Nov 08 '22 03:11

Sotirios Delimanolis


When you access a static member on an instance of a class, the Java compiler completely ignores the runtime value (and even class) of the variable and uses the member belonging to the declared class. In this case, your code is equivalent to:

favorite();
System.out.println(Test.mountain);

Even if you had code like this:

public class SubTest extends Test {
    static String mountain = "Kilimanjaro";
}

...
Test foo = new SubTest();
System.out.println(foo.mountain);

you'll still get the value on the Test class.

like image 45
chrylis -cautiouslyoptimistic- Avatar answered Nov 08 '22 02:11

chrylis -cautiouslyoptimistic-