Static fields on a null reference in Java

java, static

Solution

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

Problem

`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?

Original source

Related problems