In this tutorial, you will learn about Java instanceof operator in detail with the help of examples.
The instanceof is a binary operator used to test if an object is of a given type. The result of the operation is either true or false. It's also known as type comparison operator because it compares the instance with type.
result = objectName instanceof className;
In the left hand side of instanceof operator we use to write the object name and in the right hand side we use to write the class name. It returns true if the specified object is an instance of the specified class name, else it returns false.
class Test
{
public static void main(String args[])
{
Test t=new Test();
System.out.println(t instanceof Test);
}
}
output
true
class Test
{
public static void main(String args[])
{
Test t=null;
System.out.println(t instanceof Test);
}
}
output
false
class Test
{
public static void main(String args[])
{
Test t=new Test();
System.out.println(t instanceof Object);
}
}
output
true
Note: Every class is initially a subclass of Object class.
When Subclass type refers to the object of Parent class, it is known as downcasting. If we perform it directly, compiler gives Compilation error. If you perform it by typecasting, ClassCastException is thrown at runtime. But if we use instanceof operator, downcasting is possible.
class Animal {}
class Dog extends Animal
{
public void displayInfo()
{
System.out.println("Hello,I am a dog");
}
}
class CodeMistic
{
public static void main(String[] args)
{
Dog d1 = new Dog();
Animal a1 = d1; // Upcasting
if (a1 instanceof Dog)
{
Dog d2 = (Dog)a1; // Downcasting
d2.displayInfo();
}
}
}
Output:
Hello,I am a dog