The instanceof operator in Java is used to indicate at run time whether an object is an instance of a particular class. Instanceof Indicates whether this object is an instance of this particular class or its subclasses by returning a Boolean value.
Usage:
Result = Object Instanceof class
Parameters:
Result: Boolean type.
Object: Required option. An arbitrary object expression.
Class: Required option. Any of the defined object classes.
Description
If object is an instance of class, the instanceof operator returns TRUE. Returns False if object is not an instance of the specified class, or if object is null.
Examples are as follows:
Package com.instanceoftest; Interface a{} class B implements a{} class C extends B {} class Instanceoftest {public static void main (string[] args) {A a=null; B B=null; Boolean res; System.out.println ("Instanceoftest test Case 1:------------------"); res = a instanceof A; System.out.println ("A instanceof A:" + res); res = b instanceof B; System.out.println ("b instanceof B:" + res); System.out.println ("/ninstanceoftest test Case 2:------------------"); A=new B (); B=new B (); res = a instanceof A; System.out.println ("A instanceof A:" + res); res = a instanceof B; System.out.println ("A instanceof B:" + res); res = b instanceof A; System.out.println ("b instanceof A:" + res); res = b instanceof B; System.out.println ("b instanceof B:" + res); System.out.println ("/ninstanceoftest test Case 3:------------------"); B b2= (c) New C (); Res = B2 instanceof A; System.out.println ("B2 instanceof A:" + res); res = B2 instanceof B; System.out.println ("B2 instanceof B:" + res); res = B2 instanceof C; System.out.println ("B2 instanceof C:" + res); }}/*result:instanceoftest test Case 1:------------------a instanceof a:falseb instanceof b:falseinstanceoftest test CAs E 2:------------------a instanceof A:truea instanceof b:trueb instanceof a:trueb instanceof b:trueinstanceoftest test Case 3:------------------B2 instanceof a:trueb2 instanceof b:trueb2 instanceof c:true * *
The instanceof operator in Java