← Back to Core Java Course | Chapter 7: OOP Core | Lesson 10 of 11

Java instanceof Operator

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?

java
class Animal {}
public class Main {
	public static void main(String[] args) {
		Animal a = new Animal();
		System.out.println(a instanceof Animal);
	}
}

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

java
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
	}
}

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

java
class Animal {}
public class Main {
	public static void main(String[] args) {
		Animal a = null;
		System.out.println(a instanceof Animal); // always false for null
	}
}

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

java
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
	}
}

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

java
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 run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.