Monday, January 23, 2006
Random Java Trivia
Random Java Trivia: "When does the following code not throw a NullPointerException? MyClass obj = null; obj.doSomething(); "
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 invokestatic 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.
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 invokestatic 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.