What is purpose of instance of operator?

instanceof is an operator in Java. It has two operands, first operand is an object and second operand is a class or an interface.

How to use instanceof operator?
boolean b = object_name instanceof class_name;
instanceof operator returns true if the object_name is an instance of a class_name class or an interface, else returns false.

It is basically used to check in run time, before performing or invoking certain methods with an object.

Since, we generally know the type of objects, it may not be required to use instanceof operator.

However in some special scenarios like storing different objects beloging to different classes in a inheritance Hierarchy, and fetching them back, to invoke certain methods. It may be needed to identify type of object during run time.

interface Vehicle{}
class TwoWheeler implements Vehicle{
public void drive_forward(){System.out.println("drive_forward() method");}
class FourWheeler implements Vehicle{
public void drive_backward(){System.out.println("drive_backward() method");}

class Test{
void call(Vehicle p){//upcasting
if(p instanceof TwoWheeler){
TwoWheeler a=(TwoWheeler)p;//Downcasting
if(p instanceof FourWheeler){
FourWheeler b=(FourWheeler)p;//Downcasting


class MainDemo{
public static void main(String args[]){
Vehicle obj=new FourWheeler();
Test t1=new Test();

You may also like to read:
Generic version of HashSet
How to use HashSet to store objects
Packages in which comparator and comparable interfaces are defined