Monday, January 13, 2020

instanceof operator

The instanceof operator


Java instanceof operator is used to identify the type of the object. The instanceof operator examines if an object is an instance of the given class or not. instanceof is a comparison operator because it compares an instance with a provided type. It returns either true or false. If any object is compared using instanceof operator with null value then it will always return a false. instanceof handy tool when there are several objects of different classes available and we need to make sure that what is the type of the object.

For example, in the example below, we can if a is an object of A or not,

class A{
    
}
public class Test {

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


Output:
True

Upcasting and Downcasting

It means we can obtain run-time type information about an object with the instanceof operator. One more important feature provided by Java is Typecasting. It can be upcasting or downcasting. Upcasting can be done easily, but in order to perform downcasting, we should check the types otherwise we may get
ClassCastException

upcasting or downcasting

instanceof Example


interface Wings{}

class Bird implements Wings{}

class Parrot extends Bird{}

public class Demo {
     public static void main(String[] args) {
              Wings w1=new Bird();
              Wings w2=new Parrot();
              Bird b=new Bird();
              Parrot p=new Parrot();
              System.out.println(w1 instanceof Wings);//true
              System.out.println(w1 instanceof Bird);//true
              System.out.println(w2 instanceof Bird);//true
              System.out.println(b instanceof Bird);//true
              System.out.println(p instanceof Bird);//true
              System.out.println(p instanceof Parrot);//true
              System.out.println(p instanceof Wings);//true
              System.out.println(w2 instanceof Parrot);//true
              System.out.println(b instanceof Parrot);//false
              System.out.println(w1 instanceof Parrot);//false
              p=null;
              System.out.println(p instanceof Bird);//false
            }
}


Output

true
true
true
true
true
true
true
true
false
false
false


Video Tutorial