What is Java instanceOf Operator?
- It is a binary operator, that checks whether an object is an instance of a specific class or an interface or subclass. The result will return either true or false.
- Also, known as Type Comparison Operator, because it compares the instance with type.
Syntax:
objectName instanceOf className;
Examples 1 :
Java Code
class TUF{
public static void main(String args[]){
TUF s=new TUF();
System.out.println(s instanceof TUF); //true
}
}
Output: true
Example 2(String):
Java Code
class Simple{
public static void main(String args[]){
String str1 = "TUF!";
if (str1 instanceof String)
System.out.println("str1 is an instance of the String");
else
System.out.println("str1 is NOT an instance of the String");
}
}
Output: str1 is an instance of the String
Inherited classes:
Java program to check if an object of the subclass is also an instance of the superclass:
Java Code
// superclass
class Animal {
}
// subclass
class Cat extends Animal {
}
class Main {
public static void main(String[] args) {
// create an object of the subclass
Cat c1 = new Cat();
// checks if d1 is an instance of the subclass
System.out.println(c1 instanceof Cat); // prints true
// checks if d1 is an instance of the superclass
System.out.println(c1 instanceof Animal); // prints true
}
}
Output:
true
true
In the above demo, we have created a subclass of cat that is inherited from superclass Animal. We have created object c1 of cat class.
Another Example:
Java Code
class Bird {}
class Penguin extends Bird {}
class instanceofTest {
public static void main(String[] args) {
Penguin pobj = new Penguin();
Bird bobj = new Bird();
// Is `child` class instance of `child` class?
if (pobj instanceof Penguin)
System.out.println("pobj is instance of Penguin");
else
System.out.println("pobj is NOT instance of Penguin");
// Is `child` class instance of `parent` class?
if (pobj instanceof Bird)
System.out.println("pobj is instance of Penguin");
else
System.out.println("pobj is NOT instance of Bird");
// Is the `parent` class instance of `child` class?
if (bobj instanceof Penguin)
System.out.println("pobj is instance of Bird");
else
System.out.println("pobj is NOT instance of Bird");
}
}
Output:
pobj is instance of Penguin
pobj is instance of Penguin
pobj is NOT instance of Bird
Java program to demonstrate that instanceof returns false for null:
Java Code
class Test {}
class Main {
public static void main(String[] args) {
Test tobj = null;
// A simple case
if (tobj instanceof Test)
System.out.println("tobj is instance of Test");
else
System.out.println("tobj is NOT instance of Test");
}
}
Output: tobj is NOT instance of Test
Application :
It is used when we need to typecast, to check if it’s valid or not using instanceOf Operator.
Special thanks to Amisha Kumari for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article