Java Tip #10: The instanceof-operator is null-safe

Another quick-shot Java Tip. Keeping it simple because I don't have much time currently. It's one of the lesser-known facts of the instanceof-operator and I've seen it's applicability in some sources but YMMV.


Advice

Use the Java operator instanceof for implicit null-checks. Sometimes there is the need to check for both (eg. in equals()-methods), non-null and a certain class. Instead of checking for each condition seperately one can use just the instanceof operator, which handles a null-pointer in the same manner as a non-matching class.

Code-Example

Before

...
if (field != null) {
    if (field instanceof SomeClass) {
        ...
    }
}
...

After

...
if (field instanceof SomeClass) {
    ...
}
...

Benefit

Small readability gain.

Remarks

This seems to be one of the lesser known facts about Java there can be a small confusion with other participants on the same code who interpret this to an aparently missing null-check. But this comes as no danger when the other person just re-adds the null-check, there should be no bad effect on the logic. Maybe just spread this knowledge to your participants somehow ;)

|

Similar entries

Comments

Hey, Kosi I need ur help on one project, can you please let me know ur email id so i can explain it..
Thanks..
waiting for your reply...
Regards. Ishaq.