8

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?

Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
MaheshVarma
  • 2,081
  • 7
  • 35
  • 58
  • Nice thing about C# is that this wouldn't compile because you access `mountain` from an instance and not the class (not to start a flame here, just comment) – Julián Urbano Dec 18 '13 at 04:21

3 Answers3

4

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.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
3

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.

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152
0

favorite() is a static method that returns Test type. Then you use the static variable of this class (mountain). This all works as you never use (and do not need to use) an instance of this class so there can be no null pointer exception.

Szymon
  • 42,577
  • 16
  • 96
  • 114