The instanceof operator is used to determine whether or not a reference variable contains a specific type of object reference.
Because it compares the instance to the type, the instanceof operator in Java is also known as the type comparison operator. It either returns true or false. We get false when using the instanceof operator on a variable with a null value.
Syntax:
(object) instanceof (type)
where,
object: It is an object reference variable.
type: It can be a class or an interface.
Simple Example:
// Java Program to Illustrate instanceof Keyword
// Importing required I/O classes
import java.io.*;
// Main class
class Demo {
public static void main(String[] args)
{
// Creating object of class inside main()
Demo object = new Demo();
// Returning instanceof
System.out.println(object instanceof Demo);
}
}
Output:
true
Parent reference referring to a Child is an instance of Child Example
class Parent { }
class Child extends Parent { }
class Test
{
public static void main(String[] args)
{
// Reference is Parent type but object is
// of child type.
Parent cobj = new Child();
if (cobj instanceof Child)
System.out.println("cobj is instance of Child");
else
System.out.println("cobj is NOT instance of Child");
}
}
Output:
cobj is an instance of Child
instanceof in java with a variable that has null value
class Dog2{
public static void main(String args[]){
Dog2 d=null;
System.out.println(d instanceof Dog2);//false
}
}
Output:
false
Downcasting with the java instanceof operator
Downcasting occurs when a Subclass type refers to a Parent class object. If we do it manually, the compiler will give us a Compilation Error. You’ll get a ClassCastException at runtime if you do it using typecasting. Downcasting is possible, though, if we use the instanceof operator.
Dog d=new Animal();//Compilation error
If we perform downcasting by typecasting, ClassCastException is thrown at runtime.
Dog d=(Dog)new Animal();
//Compiles successfully but ClassCastException is thrown at runtime
downcasting with instanceof:
class Animal { }
class Dog3 extends Animal {
static void method(Animal a) {
if(a instanceof Dog3){
Dog3 d=(Dog3)a;//downcasting
System.out.println("ok downcasting performed");
}
}
public static void main (String [] args) {
Animal a=new Dog3();
Dog3.method(a);
}
}
Output:
ok downcasting performed
Note: also read about the Final keyword in Java
Follow Me
If you like my post please follow me to read my latest post on programming and technology.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Leave a Comment