Random Java Trivia

by Charles Miller on January 17, 2006

When does the following code not throw a NullPointerException?

MyClass obj = null;

This one came up on the Apple java-dev mailing-list the other day. The answer (in case you haven't guessed) is: when doSomething() is a static method of MyClass.

It's pretty obvious when you think about it. The doSomething() method call gets compiled into an <a href="http://java.sun.com/docs/books/vmspec/2nd-edition/html/Instructions2.doc6.html#invokestatic">invokestatic</a> bytecode. invokestatic doesn't need an object reference on the stack, so after compilation the obj variable isn't even being doesn't even need to be referenced any more, let alone dereferenced.

This sort of language trivia is unlikely to be useful to anyone not just about to go into a certification exam, or entirely the wrong kind of programmer interview. It's just one of those mildly interesting edge-cases, like what happens when you throw null, or the maximum number of parameters you can pass to a method, or how to change the value of a constant string.

If you find yourself in a situation where have to know the answer to any of these questions, turn around and run.

Previously: Should We Talk About the Weather?

Next: Build One to Throw Away?