instanceof operator

In Java, instanceof operator is used to check the type of an object at runtime. It is the means by which your program can obtain run-time type information about an object. instanceof operator is also important in case of casting object at runtime. instanceof operator return boolean value, if an object reference is of specified type then it return true otherwise false.


Example of instanceOf

public class Test
{
    public static void main(String[] args)
    {
      Test t= new Test();
      System.out.println(t instanceof Test);
      }
}

Output :

true

Downcasting

downcasting in java


Example of downcasting with instanceof operator

class Parent{ }

public class Child extends Parent
{
    public void check()
    {
        System.out.println("Sucessfull Casting");
    }

    public static void show(Parent p)
    {
       if(p instanceof Child)
       {
           Child b1=(Child)p;
           b1.check();
       }
    }
    
    public static void main(String[] args)
    {
      
      Parent p=new Child();
      
      Child.show(p);
      
      }
}

Output :

Sucessfull Casting

More example of instanceof operator

class Parent{}

class Child1 extends Parent{}

class Child2 extends Parent{}

class Test
{
  public static void main(String[] args)
  {
      Parent p =new Parent();
      Child1 c1 = new Child1();
      Child2 c2 = new Child2();
      
      System.out.println(c1 instanceof Parent);		//true	
      System.out.println(c2 instanceof Parent);		//true	
      System.out.println(p instanceof Child1);		//false	
      System.out.println(p instanceof Child2);		//false	
      
      p = c1;
      System.out.println(p instanceof Child1);		//true	
      System.out.println(p instanceof Child2);		//false	
      
      p = c2;
      System.out.println(p instanceof Child1);		//false	
      System.out.println(p instanceof Child2);		//true	
      
   }
    
}

Output :

true
true
false
false
true
false
false
true