The instanceof Keyword : instanceof « Operators « Java Tutorial






The instanceof keyword can be used to test if an object is of a specified type.

if (objectReference instanceof type)

The following if statement returns true.

public class MainClass {
  public static void main(String[] a) {

    String s = "Hello";
    if (s instanceof java.lang.String) {
      System.out.println("is a String");
    }
  }

}
is a String

However, applying instanceof on a null reference variable returns false. For example, the following if statement returns false.

public class MainClass {
  public static void main(String[] a) {

    String s = null;
    if (s instanceof java.lang.String) {
      System.out.println("true");
    } else {
      System.out.println("false");
    }
  }

}
false

Since a subclass 'is a' type of its superclass, the following if statement, where Child is a subclass of Parent, returns true.

class Parent {
  public Parent() {

  }
}

class Child extends Parent {
  public Child() {
    super();
  }
}

public class MainClass {
  public static void main(String[] a) {

    Child child = new Child();
    if (child instanceof Parent) {
      System.out.println("true");
    }

  }

}
true








3.10.instanceof
3.10.1.The instanceof Keyword
3.10.2.Identifying Objects
3.10.3.Finding Out of what Class an Object is Instantiated
3.10.4.instanceof operator and class hierarchy