Static fields on a null reference in Java

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. […]

Leave a Comment