Java instanceof Operator: A Comprehensive Guide
Java instanceof Operator: A Comprehensive Guide
Explore how Java’s instanceof operator works, with clear examples covering basic usage, inheritance, and interfaces.
In Java, the instanceof operator lets you verify whether an object belongs to a specific class or interface. It returns true if the object’s runtime type matches the specified type, otherwise false.
objectName instanceof className;
Below is a straightforward example demonstrating the operator with a String and a user‑defined class.
Example: Basic instanceof Usage
class Main {
public static void main(String[] args) {
String name = "Programiz";
boolean result1 = name instanceof String;
System.out.println("name is an instance of String: " + result1);
Main obj = new Main();
boolean result2 = obj instanceof Main;
System.out.println("obj is an instance of Main: " + result2);
}
}
Output
name is an instance of String: true obj is an instance of Main: true
Both checks return true because name is indeed a String and obj is a Main instance.
Note: In Java, String is a reference type, not a primitive.
Using instanceof with Inheritance
The operator is invaluable when working with polymorphic hierarchies. It confirms that a subclass instance also satisfies its superclass type.
// Superclass
class Animal {}
// Subclass
class Dog extends Animal {}
class Main {
public static void main(String[] args) {
Dog d1 = new Dog();
System.out.println(d1 instanceof Dog); // true
System.out.println(d1 instanceof Animal); // true
}
}
As shown, d1 is recognized as both a Dog and an Animal, reflecting Java’s inheritance model.
Using instanceof with Interfaces
instanceof also checks whether an object implements a particular interface.
interface Animal { }
class Dog implements Animal { }
class Main {
public static void main(String[] args) {
Dog d1 = new Dog();
System.out.println(d1 instanceof Animal); // true
}
}
Here, d1 is a Dog that implements Animal, so the operator returns true.
Note: Every Java class ultimately extends java.lang.Object. Therefore, any object is also an instance of Object. For example:
d1 instanceof Object
This will always evaluate to true.
Java
- Understanding Java’s final Keyword: Variables, Methods, and Classes
- Mastering Java Inheritance: Concepts, Types, and Practical Examples
- Mastering Java Anonymous Inner Classes: Definition, Syntax, and Practical Examples
- Mastering Java’s ObjectInputStream: A Comprehensive Guide
- Mastering Java ObjectOutputStream: Serialization, Methods, and Practical Examples
- Mastering Java’s PrintStream Class: Print, Println, and Printf Explained
- Mastering Java Reader Class: Subclasses, Methods, and Practical Example
- Mastering Java Generics – Building Reusable, Type‑Safe Code
- Mastering Java File Operations with java.io – Creation, Reading, Writing & Deletion
- Java 9: Simplify Anonymous Inner Classes with the Diamond Operator