A Java instanceof array example

While working with “Java instanceof” tests recently, my curiosity was piqued and I thought I’d take a look at how the instanceof operator works when testing against a Java array.

A Java instanceof array example

To that end, I created the following Java instanceof array example class. To make my findings really stand out well, I ended up creating two different methods, instanceTester, and arrayTester, and call both of them with a simple Java String array:

/**
 * A Java ‘instanceof’ array example/test class.
 * @author alvin alexander, alvinalexander.com.
 */
public class JavaInstanceofArrayExample
{
  public static void main(String[] args)
  {
    String[] array = {"a", "b", "c"};
    instanceTester(array);
    arrayTester(array);
  }
  
  /**
   * A method that tests to see if the given object is 
   * an instance of a String.
   */
  static void instanceTester(Object object)
  {
    // see if the object is a String instance
    if (object instanceof String)
      System.out.println("object is a String");
    else
      System.out.println("object is not a String");
  }

  /**
   * A method that test to see if the given object is 
   * an instance of a String array.
   */
  static void arrayTester(Object[] objectArray)
  {
    // see if the object is a String array instance
    if (objectArray instanceof String[])
      System.out.println("objectArray is a String array");
    else
      System.out.println("objectArray is not a String array");
  }

}

(Before going on, it might be fun/helpful to make a note of what you think the output from this instanceof example will look like.)

Example program output

If you’ve used the Java instanceof operator to test against arrays before, you may have known that the program output would look like this:

object is not a String
objectArray is a String array

As you can see from the code, this happens because this test returns false:

if (object instanceof String)

while this test returns true:

if (objectArray instanceof String[])

The crazy thing about this test is that, to the best of my knowledge, I’ve never tried passing an object array into a method that had a simple Object signature, as I did in this code when calling the instanceTester method. As I was working on this article, once I saw that I could do something like this, I decided that I better try both tests: one comparison of the String array against the instanceof String test, and a second comparison of the String array against the instanceof String[] test.

Related “Java instanceof” articles

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

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.