Java Language Triva...
  Posted March 05, 2003    PermaLink    Comments (0)  

Here's an interesting snippet.....

String s = null;
boolean valid = s instanceof Object;

So is valid true or is valid false? The answer may suprise you: valid will be false. Why? Well, static type analysis may be tempting to use, and the fact that every reference type must be an Object is another tempting conclusion as well. But nether of these can be used because of the defniniton of the null object reference. C++ doesn't really have this, becuase the convention is to use 0 or NULL to "null out" a pointer. But when you build a construct into a languate you have to be explicit.

Java defines two unique properties for null, first that it is castable to any other type. You probobly knew that already. But the second unique property is that any evaluation of the instanceof operator with a null object will result in a false result. So the null object can be cast to any object but it has no type. Meditate on that one for a while...

This isn't totally useless trivia either, I use it all the time to eliminate redundant null pointer checks. Cosinder this code snippet...

public void tweakElement(org.w3c.dom.Node n) {
    if (n instanceof org.w3c.dom.Element) {
        // do random tweaking here

What if the user calls tweakElement(null)? How will it behave then? Well, the same thing as if they pass a org.w3c.dom.Attribute: it's a no-op. Since the null check is built into the instanceof check I can go along in the tweaking code block assuming that not only do I have an Element, but that I have a non-null object as well. It's not a substitute for != null, but if you are checking class at the same time it's already done for you.

Trackback URL
  TrackBack URL for this entry:
Post Comment

Thanks for signing in, . Now you can comment. (sign out)

(If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.)

Remember me?

Email Address: