Java Programming/Keywords/instanceof

instanceof is a keyword.

It checks if an object reference is an instance of a type, and returns a boolean value;

The <object-reference> instanceof Object will return true for all non-null object references, since all Java objects are inherited from Object. instanceof will always return false if <object-reference> is null.

Syntax:

<object-reference> instanceof TypeName

For example:

Computer code
class Fruit
 {
  //...	
 } 
 class Apple extends Fruit
 {
  //...
 }
 class Orange extends Fruit
 {
  //...
 }
 public class Test 
 {
    public static void main(String[] args) 
    {
       Collection<Object> coll = new ArrayList<Object>();
 
       Apple app1 = new Apple();
       Apple app2 = new Apple();
       coll.add(app1);
       coll.add(app2);
 
       Orange or1 = new Orange();
       Orange or2 = new Orange();
       coll.add(or1);
       coll.add(or2);
 
       printColl(coll);
    }
 
    private static String printColl( Collection<?> coll )
    {
       for (Object obj : coll)
       {
          if ( obj instanceof Object )
          {
             System.out.print("It is a Java Object and");
          }
          if ( obj instanceof Fruit )
          {
             System.out.print("It is a Fruit and");
          }
          if ( obj instanceof Apple )
          {
             System.out.println("it is an Apple");
          } 
          if ( obj instanceof Orange )
          {
             System.out.println("it is an Orange");
          }
       }
    }
 }

Run the program:

java Test

The output:

"It is a Java Object and It is a Fruit and it is an Apple"
"It is a Java Object and It is a Fruit and it is an Apple"
"It is a Java Object and It is a Fruit and it is an Orange"
"It is a Java Object and It is a Fruit and it is an Orange"

Note that the instanceof operator can also be applied to interfaces. For example, if the example above was enhanced with the interface


Computer code
interface Edible 
{
 //...
}


and the classes modified such that they implemented this interface


Computer code
class Orange extends Fruit implements Edible
 {
  ...
 }


we could ask if our object were edible.


Computer code
if ( obj instanceof Edible )
 {
   System.out.println("it is edible");
 }