Disassembling (javap -c Foo) bytecode of the Foo.java file shows information under the hood about why you don't see a NullPointerException when name is static .
With the above code, when it is parsed, it produces the following output.

If we look at the yellow field, we will see that the compiler identifies that we are trying to access the static field, and therefore it puts the getstatic statement to get the name field. Thus, it does not effectively use the instance returned from the getFoo method to get the value of the name field, and therefore no NPE is created.
If we remove the static before String name = " JavaQuiz"; , this will result in disassembled code.

Here we see that the java compiler instructs to use the getfield , and this will be called on the instance, that is, returned from the getFoo method. Thus, this will increase NPE if the getFoo method returns null .
Thus, in this case, the java compiler does the magic at compile time, i.e. if the code calls a static field, it places a getstatic statement that does not result in an object reference being used.
We can find more information on the instruction set here .
source share