The instanceof keyword is an operator in java. It checks if the given object is an instance of a specified class or interface. It returns true or false.
Let’s take a simple example first, to see how instanceof works:
public class JavaExample {
public static void main(String[] args) {
//the obj is an object of "JavaExample" class
JavaExample obj = new JavaExample();
System.out.println(obj instanceof JavaExample);
}
}
Output:
true
It returned true because obj is an object of the specified class.
How instanceof works?
- It compares the left operand (the object) with the right operand (the type specified by class name or interface name) and returns true, if the type matches else it returns false.
- When I say type of class, it means that if you compare the object of sub class with the super class using instanceof, it will still return true.
Example 1: Using instanceof with strings
public class JavaExample {
public static void main(String[] args) {
String str = "Java is so cool";
System.out.println(str instanceof java.lang.String);
}
}
Output:
true
Example 2: Using instanceof with null
If an object contains null, then it will always return false.
public class JavaExample {
public static void main(String[] args) {
JavaExample obj = null;
System.out.println(obj instanceof JavaExample);
}
}
Output:
false
Example 3: subclass and superclass
Here, we have a superclass and a subclass. When we compared the object of subclass with the superclass, the instanceof operator returned true.
class MyClass{
}
public class JavaExample extends MyClass{
public static void main(String[] args) {
JavaExample obj = new JavaExample();
//checking subclass object for superclass type
System.out.println(obj instanceof MyClass);
}
}
Output:
true
Example 4: instanceof with interface
interface MyInterface{
}
public class JavaExample implements MyInterface{
public static void main(String[] args) {
JavaExample obj = new JavaExample();
//comparing subclass object with parent interface
System.out.println(obj instanceof MyInterface);
}
}
Output:
true