A Java “instanceof null” example

You might think that when the Java instanceof operator is used to test a null reference, such as a null reference to a String, instanceof would realize that even though the reference is currently null, it is a reference to a String, so you might expect instanceof to return true ... but it doesn’t.

Java instanceof null - example

To demonstrate this, I created an example Java class to show this instanceof null behavior:

 * An instanceof example, showing what "instanceof null" returns.
 * By Alvin Alexander, http://alvinalexander.com
public class JavaInstanceofNullExample
  public static void main(String[] a)
    // create a null string
    String myReference = null;
    // use instanceof to see if myReference is of the type String
    if (myReference instanceof String)
      // this line is not printed
      System.out.println("myReference is a String");
      // this line is printed because "instanceof null" returns false
      System.out.println("instanceof returned false");

As the comments show, this example class will print the following output:

instanceof returned false

But Java is strongly typed ...

I’m not a big fan of this behavior when dealing with a null reference. Because Java is a strongly-typed language — and that’s one of its strengths — even though myReference is currently null, we know that it was declared to be of type String, and that can’t change, so in my world view, instanceof should return true, even when the reference is null.

My guess is that it works this way because Java was initially developed in the early-to-mid 1990s, and this may have been a way of making the code faster, or, I could be wrong, and it may have just been a design decision.

Related “Java instanceof” articles

Here are links to some of my other Java instanceof tutorials:


instanceof checks if the object is an _instance_ of a type. null is no instance at all (you don't say "new null"), it is undefined and non instantiated. So it's perfectly reasonable that null instanceof Object returns false.

For the same reason "instanceof int" doesn't work, because you cannot instantiate int's (however, instanceof Integer works).

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.