« NetBeans.org Want You to Click My Links! | Main | Use The Source, Duke! »

Java Language Triva...

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.

About

This page contains a single entry from the blog posted on March 5, 2003 12:10 PM.

The previous post in this blog was NetBeans.org Want You to Click My Links!.

The next post in this blog is Use The Source, Duke!.

Many more can be found on the main index page or by looking through the archives.

Powered by
Movable Type 3.33