However, this code is a question in a certification book. The answer for the question suggests it is a runtime exception instead of a compilation error. I was thinking that the compiler would see a null pointer in the code and cause a compile error. Why is it a runtime exception instead of a compile time error?
Because , when compiler compiles the code, it saw everything is perfect, as per "rules" and and this statement e2.e = e1; has a valid reference "e2" , which pointing to nothing "null" object and retrieving its 'e' instance variable (object here) . This is fine as per compilers perspective.
When code actually runs, we are retrieving the 'e' instance variable , from an "null" nothing object, hence the JVM , complains that "he cant find the things as he expected" and he throws an runtime exception , stating "NullPointerException" ..
Pointers being null is something that occurs at runtime; the compiler has no concept of what a particular piece of code might or might not do at runtime, so it doesn't try to guess what might go wrong. It can't do that in general anyway, so why bother doing it for simple cases where that's possible?