The instanceof operator in Java is used to indicate at runtime whether an object is an instance of a specific class. Instanceof returns a Boolean value to indicate whether the object is an instance of this particular class or its subclass.
Usage:
Result = Object instanceof class
Parameters:
Result: boolean type.
Object: required. Any object expression.
Class: required. Any defined object class.
Note:
If an object is an instance of class, the instanceof operator returns true. If the object is not an instance of the specified class, or the object is null, false is returned.
Example:
Package com. instanceoftest;
Interface {}
Class B implements {
}
Class C extends B {
}
Class instanceoftest {
Public static void main (string [] ARGs ){
A A = NULL;
B = NULL;
Boolean res;
System. Out. println ("instanceoftest Test Case 1 :------------------");
Res = A instanceof;
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;
System. Out. println ("A instanceof A:" + Res );
Res = A instanceof B;
System. Out. println ("A instanceof B:" + Res );
Res = B instanceof;
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;
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: false
B instanceof B: false
Instanceoftest Test Case 2 :------------------
A instanceof A: True
A instanceof B: True
B instanceof A: True
B instanceof B: True
Instanceoftest Test Case 3 :------------------
B2 instanceof A: True
B2 instanceof B: True
B2 instanceof C: True
*/