The instanceof operator in java, javainstanceof
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:
1 package com.instanceoftest; 2 3 4 5 interface A{} 6 class B implements A{ 7 8 } 9 class C extends B {10 11 }12 13 class instanceoftest {14 public static void main(String[] args){15 A a=null;16 B b=null;17 boolean res; 18 19 System.out.println("instanceoftest test case 1: ------------------");20 res = a instanceof A; 21 System.out.println("a instanceof A: " + res);22 23 res = b instanceof B;24 System.out.println("b instanceof B: " + res);25 26 System.out.println("/ninstanceoftest test case 2: ------------------"); 27 a=new B();28 b=new B();29 30 res = a instanceof A; 31 System.out.println("a instanceof A: " + res);32 33 res = a instanceof B;34 System.out.println("a instanceof B: " + res);35 36 res = b instanceof A;37 System.out.println("b instanceof A: " + res);38 39 res = b instanceof B;40 System.out.println("b instanceof B: " + res);41 42 System.out.println("/ninstanceoftest test case 3: ------------------");43 B b2=(C)new C();44 45 res = b2 instanceof A;46 System.out.println("b2 instanceof A: " + res);47 48 res = b2 instanceof B;49 System.out.println("b2 instanceof B: " + res);50 51 res = b2 instanceof C;52 System.out.println("b2 instanceof C: " + res);53 }54 }55 56 57 /*58 result:59 60 61 instanceoftest test case 1: ------------------62 a instanceof A: false63 b instanceof B: false64 65 instanceoftest test case 2: ------------------66 a instanceof A: true67 a instanceof B: true68 b instanceof A: true69 b instanceof B: true70 71 instanceoftest test case 3: ------------------72 b2 instanceof A: true73 b2 instanceof B: true74 b2 instanceof C: true75 76 77 78 */