Static fields on a null reference in Java

static members (static fields or static methods) in Java are associated with their respective class rather than the objects of this class. The following code attempts to access a static field on a null reference.

public class Main
{
    private static final int value = 10;

    public Main getNull()
    {
        return null;
    }

    public static void main(String[] args)
    {
        Main main=new Main();
        System.out.println("value = "+main.getNull().value);
    }
}

Although main.getNull() returns null, it works and displays value = 10. How does this code work?


That behaviour is specified in the Java Language Specification:

a null reference may be used to access a class (static) variable without causing an exception.

In more details, a static field evaluation, such as Primary.staticField works as follows (emphasis mine) - in your case, Primary = main.getNull():

  • The Primary expression is evaluated, and the result is discarded. [...]
  • 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. [...]

Because, as you said, static fields are not associated with an instance.

The ability to access static fields from an instance reference (as you are doing) is merely a syntactic sugar and has no additional meaning.
Your code compiles to

main.getNull(); 
Main.value

When ever you access a static variable or method with objects at compile time it converted to Class name. eg:

Main main = null;
System.out.println(main.value);

It will print the value of static variable value because at compile time It will be converted to

System.out.println(Main.value);

Proof:

download decompiler and Decompile your .class file to .java file and you can see all static methods or variable referred object name is automatically replaced by class name.


  1. Accessing a static member with the class name is legal, but its no were written that one cannot access the static member using the object reference variable. So it works over here.

  2. A null object reference variable is allowed to access a static class variable without throwing an exception either at compile or run time.


Static variable and method always belong to class. So when ever we create any object only non static variable and methods goes to heap along with object but static resides in method area with class. That's why when ever we try to access a static variable or method it converted to class name dot variable or method name.

Please refer below link for more detail.

http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html