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");
    }
    else
    {
      // 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, it had to initially be declared to have some type, and in this simple example 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.

Anyway ... in case you were wondering, that’s the way it works.

Related “Java instanceof” articles

I ran across this while working on some other Java instanceof tutorials, which you can find at these links: