The instanceof operator in Java is used to test whether an object is an instance of a specific class, subclass, or interface.
It returns a boolean (true or false).
objectReference instanceof ClassNameString s = "Hello";
System.out.println(s instanceof String); // true- Runtime type checking
- Safe downcasting (prevents
ClassCastException) - Checking polymorphic references
- Validating interface implementations
class Animal { }
class Dog extends Animal { }
Animal a = new Dog();
System.out.println(a instanceof Dog); // true
System.out.println(a instanceof Animal); // true
System.out.println(a instanceof Object); // trueinterface Shape { }
class Circle implements Shape { }
Shape s = new Circle();
System.out.println(s instanceof Circle); // true
System.out.println(s instanceof Shape); // trueDowncasting without checking can cause runtime errors:
Animal a = new Animal();
Dog d = (Dog) a; // ClassCastExceptionAnimal a = new Dog();
if (a instanceof Dog) {
Dog d = (Dog) a;
d.bark();
}If the reference is null, instanceof always returns false.
String s = null;
System.out.println(s instanceof String); // falseBecause null is not an instance of anything.
Consider:
class A { }
class B extends A { }
class C extends B { }If:
A obj = new C();Then:
obj instanceof A → true
obj instanceof B → true
obj instanceof C → trueBecause a C is also a B and an A.
Modern Java introduced pattern matching for instanceof:
Instead of:
if (obj instanceof String) {
String s = (String) obj;
System.out.println(s.toLowerCase());
}You can write:
if (obj instanceof String s) {
System.out.println(s.toLowerCase());
}Cleaner and avoids explicit casting.
You cannot check instances of classes that cannot be subclassed, but instanceof still works:
final class FinalClass { }
FinalClass f = new FinalClass();
System.out.println(f instanceof FinalClass); // trueArrays are also objects; you can check them:
int[] arr = new int[5];
System.out.println(arr instanceof int[]); // true
System.out.println(arr instanceof Object); // trueParent p = new Parent();
Child c = (Child) p; // WrongCorrect:
if (p instanceof Child) {
Child c = (Child) p;
}Dog d = new Dog();
System.out.println(d instanceof Animal); // true (correct)Better to use overridden methods rather than instanceof chains.
It checks whether an object is compatible with a given type at runtime.
Yes.
Always false.
To avoid ClassCastException.
Yes, from Java 16+.
-
instanceofis used to test type compatibility at runtime. -
Essential for safe downcasting.
-
Works with classes, interfaces, arrays, and inheritance.
-
Returns false for null references.
-
Modern Java allows cleaner pattern matching with instanceof.