Java instanceof Operator
In this page:
What is the instanceof Operator?
instanceof tests whether an object is an instance of a given class or interface at runtime, returning a plain boolean — it's the standard way to check an object's actual type before performing a type-specific operation, especially with polymorphic collections.
Example: What is the instanceof Operator?
class Animal {}
public class Main {
public static void main(String[] args) {
Animal a = new Animal();
System.out.println(a instanceof Animal);
}
}
Login to try C/C++/Java/PHP code in the editor
Inheritance Checks
Because subclasses are also considered instances of their parent classes, dog instanceof Animal returns true if Dog extends Animal, even though the check names the parent type rather than the object's exact concrete class.
Example: Inheritance Checks
class Animal {}
class Dog extends Animal {}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
System.out.println(dog instanceof Animal); // true: Dog extends Animal
}
}
Login to try C/C++/Java/PHP code in the editor
Checking Null References
A null reference is never an instance of anything, so instanceof on a null variable always evaluates to false regardless of what class you're checking against — this makes instanceof a safe way to check a variable's type without risking a NullPointerException first.
Example: Checking Null References
class Animal {}
public class Main {
public static void main(String[] args) {
Animal a = null;
System.out.println(a instanceof Animal); // always false for null
}
}
Login to try C/C++/Java/PHP code in the editor
Object Class Checks
Since every class in Java implicitly extends Object, checking any non-null object instance against Object with instanceof will always return true — it's rarely useful on its own but illustrates how deep the class hierarchy actually goes.
Example: Object Class Checks
class Animal {}
public class Main {
public static void main(String[] args) {
Animal a = new Animal();
System.out.println(a instanceof Object); // true: every class extends Object
}
}
Login to try C/C++/Java/PHP code in the editor
Interface Checks
instanceof isn't limited to classes — you can also check whether an object's class implements a particular interface, which is common when you need to confirm an object supports a capability (like Comparable) before calling methods that require it.
Example: Interface Checks
interface Flyable {}
class Bird implements Flyable {}
public class Main {
public static void main(String[] args) {
Bird bird = new Bird();
System.out.println(bird instanceof Flyable);
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: