Java static field from zero

I found this code on the Internet and would like someone to explain it to me ...

public class Foo { static int fubar = 42; public static void main(String[] args) { System.out.println(((Foo) null).fubar); } } 

This code compiles and works correctly, outputting result 42 .

How is it possible that the fubar variable fubar accessed from null without throwing a NullPointerException ?

+7
source share
3 answers

Since the fubar field fubar declared static , there is only one field anywhere that is actually called Foo.fubar . Each instance of Foo shares this copy. When you access this field from a Foo object, Java does not try to reference the object to find it. Instead, it searches for an object in a specially defined place that can be accessed regardless of any link. Therefore, if you try to find this field of a null object, you can do this without raising any NullPointerException , since the object is never referenced.

EDIT : Bytecode is definitely fine! Given this source file:

 public class Foo { static int fubar; public Foo() { ((Foo)null).fubar = 137; } } 

The bytecode is generated here:

 0: aload_0 1: invokespecial #1; //Method Object."<init>":()V 4: aconst_null 5: checkcast #2; //class Foo 8: pop 9: sipush 137 12: putstatic #3; //Field fubar:I 15: return 

Note that line 12 uses the putstatic , which stores the value in the static field. It does not refer to a recipient object of any type. In fact, if you notice that the generated bytecode (lines 4-8) performs a null to Foo listing, but then immediately pops up the op code to pull it out of the stack. He never referenced anywhere in the bytecode.

+4
source

In fact, it does not look for a field on null , because static methods and fields do not require an instance. Listing makes the expression type Foo , and fubar is a known static field on Foo , so the compiler and the JVM have no problem.

Usually you should access the field by specifying Foo.fubar . However, Java is good enough to provide a shortcut: if you try to access a static field or method in an instance expression of a given type, it will treat it as if you said [SomeType].theField . What's going on here.

+10
source

fubar is a static member that gives null, just highlights the distribution of static variables at compile time, rather than at run time. A more general and equivalent way to access a static variable is Foo.fubar

+1
source

All Articles