instanceof

 

  This is Java's only named operator.  It is a word - not symbols like all the other operators.

 

  Like the method named substring( ) from the String and StringBuffer classes, and the method lineno( ) from StreamTokenizer, the word instanceof does not have a capital letter inside it where you would normally think there might be one.  i.e.

 

Saying subString( ), lineNo( ), or instanceOf, with the typical imbedded capital letter for the second word, are all incorrect spellings and will not compile. 

 

  You cannot use instanceof to arbitrarily test for class participation by an object.  It only tests for whether or not the object has been instantiated as an instance of its own class type.  The reason you can't test for a class type is that instanceof expressions will not compile if an incorrect class type is named in the statement.  i.e.

 

Double D = new Double( 0 );     then  

if ( D instanceof Float )            will not compile because of the presence of Float

 

  instanceof returns true for widening types also.  This means it returns true for all of an object reference’s higher level classes.  i.e.

 

Integer I = new Integer( 5 ); 

if ( I instanceof Integer )             returns true.

if ( I instanceof Number )         also returns true.

 

  You must put an object reference on the left side of an instanceof  expression.  On the right side you must put a class name, an interface name, or a named Array.  i.e.

 

if ( object instanceof String )                works.

if ( object instanceof byte[  ] )               works.

if ( objecta instanceof objectb )                 will not compile.

if ( String  instanceof Object )               will not compile.

 

  You cannot use instanceof to compare the class types of two object references.  Instead, to do so, you should say:

 

if (objecta.getClass( ) == objectb.getClass( ) )

 

A problem with the above is that it will throw a NullPointerException if either object is null. 

To avoid this possibility and still get the job done, say:

 

if ( ( objecta != null & objectb != null )  &&  objecta.getClass( ) == objectb.getClass( ) )

 

  You cannot use instanceof to see if something is an array in general.  i.e.

 

byte[ ] b = new byte[ 2 ];  

if (  b instanceof byte[  ] )  tests for a byte array (only), but it will not compile if the array is not of type byte[ ].  This situation renders the test somewhat useless.

 

Saying  if ( b instanceof [  ] )  will never compile.

 

  To test for the presence of arrays in general, use the .isArray( ) method from the Class class.  i.e.

Still using the above example with b:

 

if( b.getClass( ).isArray( ) ) returns true.

 

  instanceof always returns a false for any object reference which has been set to null – even if the object in question actually belongs to the class named.  i.e.

 

Object O = null; 

if ( O instanceof  Object )  returns false becaue O is null, even though O is indeed an Object.