DEV Community

Rajesh Bhola
Rajesh Bhola

Posted on

`instanceof` Operator in Java — Part 1

The instanceof operator is one of the most useful operators in Java for checking an object's type at runtime. It helps determine whether an object belongs to a particular class, one of its parent classes, or an implemented interface.

The instanceof operator is commonly used before type casting to prevent ClassCastException, making your code safer and more reliable.

Let's learn how it works with simple explanations and practical examples.


What Is the instanceof Operator?

The instanceof operator checks whether an object is an instance of a particular type.

It always returns a boolean value:

  • true if the object belongs to the specified type.
  • false otherwise.

Syntax

objectReference instanceof Type
Enter fullscreen mode Exit fullscreen mode

Where:

  • objectReference → Reference to an object.
  • Type → A class or interface.
  • Return type → boolean

Why Do We Need instanceof?

Suppose a method returns an Object.

Object employee = getEmployee();
Enter fullscreen mode Exit fullscreen mode

The actual object might be:

  • Developer
  • Manager
  • Customer

Before converting the object into a specific type, we should verify its runtime type.

Example

Object employee = getEmployee();

if (employee instanceof Developer) {

    Developer developer = (Developer) employee;

    developer.writeCode();

}
Enter fullscreen mode Exit fullscreen mode

Using instanceof prevents invalid casts and avoids ClassCastException.


Real-World Example

Suppose we have a list containing different types of objects.

Object object = list.get(0);

if (object instanceof Student) {

    Student student = (Student) object;

    student.study();

}
else if (object instanceof Customer) {

    Customer customer = (Customer) object;

    customer.placeOrder();

}
Enter fullscreen mode Exit fullscreen mode

This pattern is very common in enterprise Java applications.


Rule 1: Returns true for the Object's Class, Parent Classes, and Implemented Interfaces

Consider this example.

Thread thread = new Thread();

System.out.println(thread instanceof Thread);
System.out.println(thread instanceof Object);
System.out.println(thread instanceof Runnable);
Enter fullscreen mode Exit fullscreen mode

Output

true
true
true
Enter fullscreen mode Exit fullscreen mode

Why?

The Thread class is declared like this (simplified):

public class Thread extends Object implements Runnable {
    ...
}
Enter fullscreen mode Exit fullscreen mode

Therefore, every Thread object is:

  • A Thread
  • An Object
  • A Runnable

This relationship is often called the IS-A relationship.


Visual Representation

           Object
              ▲
              │
          Thread
              ▲
              │
        implements
              │
         Runnable
Enter fullscreen mode Exit fullscreen mode

So,

thread instanceof Thread
Enter fullscreen mode Exit fullscreen mode

returns

true
Enter fullscreen mode Exit fullscreen mode

because the object is a Thread.

Similarly,

thread instanceof Object
Enter fullscreen mode Exit fullscreen mode

returns

true
Enter fullscreen mode Exit fullscreen mode

because every Java object ultimately extends Object.

Finally,

thread instanceof Runnable
Enter fullscreen mode Exit fullscreen mode

returns

true
Enter fullscreen mode Exit fullscreen mode

because Thread implements the Runnable interface.


Rule 2: Type Compatibility Is Required

The compiler checks whether the object reference and the specified type are compatible.

Compatible means one of the following:

  • Same class
  • Parent class
  • Child class
  • Implemented interface

Example

Thread thread = new Thread();

System.out.println(thread instanceof Object);
Enter fullscreen mode Exit fullscreen mode

Output

true
Enter fullscreen mode Exit fullscreen mode

This compiles because Thread is a subclass of Object.


Incompatible Types

Thread thread = new Thread();

System.out.println(thread instanceof String);
Enter fullscreen mode Exit fullscreen mode

Compile-time error

inconvertible types:
java.lang.Thread cannot be converted to java.lang.String
Enter fullscreen mode Exit fullscreen mode

Why?

Thread and String are unrelated classes.

Since a Thread object can never become a String, the compiler rejects the code before it even runs.


Rule 3: instanceof Checks the Runtime Type

One of the most important concepts is that instanceof checks the actual object created at runtime, not the declared reference type.

Example

Object developer = new String("Rajesh");

System.out.println(developer instanceof String);
Enter fullscreen mode Exit fullscreen mode

Output

true
Enter fullscreen mode Exit fullscreen mode

Although the reference type is Object, the actual object created is a String.

Therefore,

developer instanceof String
Enter fullscreen mode Exit fullscreen mode

returns

true
Enter fullscreen mode Exit fullscreen mode

Another example

Object developer = new String("Rajesh");

System.out.println(developer instanceof Object);
Enter fullscreen mode Exit fullscreen mode

Output

true
Enter fullscreen mode Exit fullscreen mode

Every String object is also an Object.


Visual Representation

developer
    │
    ▼
"Rajesh" (String Object)
Enter fullscreen mode Exit fullscreen mode

Even though the variable is declared as Object, the runtime object is a String.


Rule 4: null instanceof Always Returns false

A null reference does not point to any object.

Therefore,

System.out.println(null instanceof String);
Enter fullscreen mode Exit fullscreen mode

Output

false
Enter fullscreen mode Exit fullscreen mode

Similarly,

System.out.println(null instanceof Object);
Enter fullscreen mode Exit fullscreen mode

Output

false
Enter fullscreen mode Exit fullscreen mode

And

System.out.println(null instanceof Thread);
Enter fullscreen mode Exit fullscreen mode

Output

false
Enter fullscreen mode Exit fullscreen mode

Why?

null is simply the absence of an object.

Since there is no object, it cannot be an instance of any class or interface.

One advantage of this behavior is that you can safely write

if (employee instanceof Developer) {

    Developer developer = (Developer) employee;

}
Enter fullscreen mode Exit fullscreen mode

without first checking

employee != null
Enter fullscreen mode Exit fullscreen mode

If employee is null, the instanceof expression simply evaluates to false.


Visual Summary

                instanceof

          Does the object IS-A type?

                 │
       ┌─────────┴─────────┐
       │                   │
      Yes                 No
       │                   │
     true               false

Special Cases

Own Class          → true

Parent Class       → true

Implemented Interface → true

null               → false

Unrelated Types    → Compile-Time Error
Enter fullscreen mode Exit fullscreen mode

Common Beginner Mistakes

Mistake 1: Assuming It Checks the Reference Type

Incorrect thinking:

The variable is declared as Object, so instanceof String should be false.

Actually,

Object developer = new String("Rajesh");

System.out.println(developer instanceof String);
Enter fullscreen mode Exit fullscreen mode

returns

true
Enter fullscreen mode Exit fullscreen mode

because the runtime object is a String.


Mistake 2: Using instanceof with Unrelated Types

Thread thread = new Thread();

thread instanceof String
Enter fullscreen mode Exit fullscreen mode

This does not compile because the types are unrelated.


Mistake 3: Expecting null instanceof to Throw an Exception

String developer = null;

System.out.println(developer instanceof String);
Enter fullscreen mode Exit fullscreen mode

Output

false
Enter fullscreen mode Exit fullscreen mode

No exception is thrown.


Quick Memory Trick 🧠

instanceof checks the actual object created at runtime—not the variable's declared type.

Remember:

  • Same class → ✅ true
  • Parent class → ✅ true
  • Implemented interface → ✅ true
  • null → ❌ false
  • Unrelated types → ❌ Compile-time error

Key Takeaways

  • The instanceof operator checks whether an object belongs to a particular type.
  • It always returns a boolean.
  • It is commonly used before type casting.
  • It returns true for the object's class, parent classes, and implemented interfaces.
  • It checks the runtime type, not the reference type.
  • null instanceof X always returns false.
  • Unrelated types result in a compile-time error.

Happy Coding!

Top comments (0)