Instance Of Operator

Instance Of Operator

Syntax:-   t instanceof x

t ==> Object / Obj reference.

x ==> class name / interface

Ex:-

  • Thread t = new Thread ( ) ;
  • System.out.println ( t instanceof Thread ) ; // true
  • System.out.println ( t instanceof Object ) ; // true
  • System.out.println ( t instanceof Runnable ) ; // true
  • System.out.println ( t instanceof String ) ; // compile time error  //incovertible type found Thread, required String

To use instanceof operator some relationship  between argument type i.e either parent to child or child to parent otherwise we will get compile time error.

Where ever we are  checking parent Object is of child type or not then we will get false as the o/p.

Object  o = new Object ( c) ;

System.out.println ( o instanceof String ) ; // false

For any class or interface ‘x’  ” null instanceof x ” is always returns false.

Leave a Reply