This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
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?
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com