Basically, you check if an object is an instance of a specific class. You normally use it, when you have a reference or parameter to an object that is of a super class or interface type and need to know whether the actual object has some other type (normally more concrete).

Example:

public void doSomething(Number param) {
  if( param instanceof Double) {
    System.out.println("param is a Double");
  }
  else if( param instanceof Integer) {
    System.out.println("param is an Integer");
  }

  if( param instanceof Comparable) {
    //subclasses of Number like Double etc. implement Comparable
    //other subclasses might not -> you could pass Number instances that don't implement that interface
    System.out.println("param is comparable"); 
  }
}

Note that if you have to use that operator very often it is generally a hint that your design has some flaws. So in a well designed application you should have to use that operator as little as possible (of course there are exceptions to that general rule).

Answer from Thomas on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › java › instanceof-keyword-in-java
instanceof Keyword in Java - GeeksforGeeks
July 23, 2025 - In Java, instanceof is a keyword used for checking if a reference variable contains a given type of object reference or not. Following is a Java program to show different behaviors of instanceof.
🌐
Baeldung
baeldung.com › home › java › core java › java instanceof operator
Java instanceof Operator | Baeldung
May 11, 2024 - In Java, every class implicitly inherits from the Object class. Therefore, using the instanceof operator with the Object type will always evaluate to true:
Discussions

instanceof - concept does not match actual use
The compiler only complains about instanceof if there is absolutely no way of it returning true with the given arguments. If there is even the smallest chance that it's true, it will allow the use. I could tell you exactly why it doesn't work if you show me the code. More on reddit.com
🌐 r/learnjava
15
3
August 11, 2016
programming practices - Replacement for instanceof Java? - Software Engineering Stack Exchange
So I'm fairly new to programming in the real world (outside of academic projects) and have come across lots of posts saying that using instanceof is a bad thing to use to determine what class a spe... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
January 18, 2013
inheritance - Java instanceof and Clean architecture - Software Engineering Stack Exchange
It seems to me that there is a conflict between clean architecture and the recommendation not to use instanceof. Consider the following code: class ParentEntity { } class AEntity extends ParentEnt... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
August 2, 2021
[Java] How to get around using instanceof?
What you're supposed to do is use polymorphism instead of instanceof. There are rare cases where instanceof is okay, but the vast majority of the time you can solve the same problem using polymorphism instead. A typical approach to this would be for Job to just have a list of Tasks. It doesn't know, or care, what type of Task each one is. When it's time to execute a task, it just calls task.execute(). Each subclass of Task, like TaskType1, TaskType2, etc. can override execute() and do whatever it needs to do. But Job doesn't really need to know or care which task type it is - all it knows is that it has a Task (or some subclass of Task) and it can tell that Task to execute. Does that make sense? If that won't work for you, can you clarify exactly what won't work? Hopefully we can figure out a design that will work for you. More on reddit.com
🌐 r/learnprogramming
7
1
November 15, 2016
🌐
W3Schools
w3schools.com › java › ref_keyword_instanceof.asp
Java instanceof Keyword
The instanceof keyword compares the instance with type. The return value is either true or false. Read more about objects in our Java Classes/Objects Tutorial.
🌐
Oracle
docs.oracle.com › en › java › javase › 17 › language › pattern-matching-instanceof.html
Pattern Matching for instanceof - Java
October 20, 2025 - A pattern is a combination of a predicate, or test, that can be applied to a target and a set of local variables, called pattern variables, that are assigned values extracted from the target only if the test is successful. The predicate is a Boolean-valued function of one argument; in this case, it’s the instanceof operator testing whether the Shape argument is a Rectangle or a Circle.
🌐
DataCamp
datacamp.com › doc › java › instanceof
instanceof Keyword in Java: Usage & Examples
Java keywordsIntroduction To JavaJava File HandlingJava Language BasicsJava ArraysJava Object-Oriented Programming ... The instanceof keyword in Java is a binary operator used to test whether an object is an instance of a specific class or implements a particular interface.
Find elsewhere
🌐
Reddit
reddit.com › r/learnjava › instanceof - concept does not match actual use
r/learnjava on Reddit: instanceof - concept does not match actual use
August 11, 2016 -

Hello,

It is my understanding that the instanceof keyword is used to determine whether an object instance is in the inheritance hierarchy of a class/interface, ex. earth instanceof Planet. This returns a boolean. Easy enough to understand.

Why does the compiler throw a fit if I use instanceof on an object instance that isn't in the inheritance hierarchy? Ex. dog instanceof Planet. If it doesn't allow testing of unrelated objects, what is the point? It should just return false in this example according to what I've gathered. But if the compiler mandates that the two things are related in the first place, instanceof would always return true. Not sure what I'm not understanding.

I've read a few things dissuading the use of instanceof altogether because it reflects poor OO design so I don't plan to actually use it much if at all, but want to deepen my understanding of Java and I haven't found an explanation of the contradiction above yet.

Thanks in advance.

🌐
Armedia
armedia.com › home › blog › “instanceof”, why and how to avoid it in code
Java “instanceOf”: Why And How To Avoid It In Code
November 23, 2019 - The java “instanceof” operator is used to test whether the object is an instance of the specified type (class or subclass or interface). It is also known as type comparison operator because it compares the instance with type.
Top answer
1 of 4
17

The reason instanceof is discouraged is that it's not OOP.

There should be no reason for the caller/user of an object to know which concrete class it is an instance of beyond which type the variable it is declared as.

If you need different behavior in subclasses add a method and implement them differently.

2 of 4
9

instanceof isn't necessarily a bad thing, however it is something that one should look at.

An example of where it works correctly is in a place where one gets a collection of the base type and you only want the ones of a subtype. Getting the network addresses from NetworkInterface.getNetworkInterfaces() returns back NetworkInterface objects which have a collection of InetAddress objects, some of which are Inet4Address and some are Inet6Address. If one wants to filter the collection for Inet4Address objects, it is necessary to use instanceof.

In the situation that is being described in the original post, there is a Base class, something that extends that base class and something that extends the extended class. While not completely informative, this seems to have the underpinnings of some less than ideal design.

When you are returning a base class unless there is good reason for it being designed that way (backwards compatibility between specifications of an earlier version) you shouldn't be trying to peek at the underlying types. If you are returned a Set, you know you are getting a set. It allows the developer to later change his or her mind to return a more specific type (SortedSet) or change the underlying type (HashSet to TreeSet) without breaking anything.

Reconsider your design of how the objects are structured and parented to see if one can make an better class model that is doesn't require a distinction of types.

🌐
Programiz
programiz.com › java-programming › instanceof
Java instanceof (With Examples)
Become a certified Java programmer. Try Programiz PRO! ... The instanceof operator in Java is used to check whether an object is an instance of a particular class or not.
🌐
Medium
medium.com › @AlexanderObregon › how-javas-instanceof-operator-works-09071a27cd3b
How Java’s instanceof Operator Works | Medium
February 28, 2025 - The instanceof operator does not compare the declared type of a reference; it inspects the actual object’s class at runtime. Under the hood, the Java compiler translates instanceof into a dedicated bytecode instruction (instanceof).
Top answer
1 of 9
3

If you want to add a method to a class hierarchy without actually adding the method, consider the Visitor Pattern. You could create a validation visitor, and let each entity select the appropriate method of the visitor.

First, your ParentEntity class hierarchy would need a bit of boilerplate to support visitors:

interface EntityVisitor<T> {
  T visitA(AEntity a);
  T visitB(BEntity b);
}

class ParentEntity {
  <T> T accept(EntityVisitor<T> v);
}

class EntityA extends ParenEntity {
  ...
  @Override <T> T accept(EntityVisitor<T> v) {
    return v.visitA(this);
  }
}

Next, we can implement and use a visitor that performs validation.

class Validation implements EntityVisitor<Void> {
  EntityRepository repository;
  ...
  @Override Void visitA(AEntity a) { ... }
  @Override Void visitB(BEntity b) { ... }
}

class EntityRepository ... {
  void save(List<ParentEntity> list) {
    list.ForEach(e -> {
      e.accept(new Validation(this));
      ...
    });
  }
}

The validation visitor can have access to both the entity and the repository (in order to make further queries), and will therefore be able to perform the full validation.

Using such a pattern has advantages and disadvantages compared to an instanceof check and compared to moving the validation logic into the entities.

  • An instanceof is a much simpler solution, especially if you only have very few entity types. However, this could silently fail if you add a new entity type. In contrast, the visitor pattern will fail to compile until the accept() method is implemented in the new entity. This safety can be valuable.

  • While this pattern ends up having the same behaviour as adding a validate() method to the entities, an important difference is where that behaviour is located and how our dependency graph looks. With a validate() method, we would have a dependency from the entities to the repository, and would have referential integrity checks intermixed with actual business logic. This defeats the point of an Onion Architecture. The visitor pattern lets us break this dependency and lets us keep the validation logic separate from other business logic. The cost of this clearer design structure is extra boilerplate in the form of the EntityVisitor interface and the accept() method that must be added to all entities in the relevant class hierarchy.

Whether these trade-offs are worth it is your call. You know your codebase best, and you have the best idea how it might evolve.

However, performing validation based on the result of multiple queries can lead to data integrity problems. The repository should either make sure to use database transactions (and offer an API that clearly communicates when modifications have been committed), or the relevant integrity checks should be done within the database, e.g. using constraints in an SQL database. In some cases, the validation checks can also be expressed as part of an insert or update query.

2 of 9
2

I know what I am about to answer is not exactly good practice but if you want to avoid instanceof's and have a generic way to call the respective method for that subclass you could use reflection:

Method m = EntityRepository.class.getMethod("validate", e.getClass());
m.invoke(this, e);

Of course, this will have a negative effect on performance and in some ways maintainability (with the only upside being less code).

Regarding the performance overhead, you can somewhat mitigate it by loading all the methods at startup:

Map<Class<?>, Method> methods = new HashMap<>();
Reflections reflections = new Reflections(ParentEntity.class, new SubTypesScanner());
Set<Class<? extends Animal>> subclasses = reflections.getSubTypesOf(ParentEntity .class);
for (Class<?> c : subclasses) {
    methods.put(c, Solution.class.getMethod("makeTalk",c));
}

Where Reflections comes from the Reflections library

And then just call the method using:

methods.get(e.getClass()).invoke(this, e)
🌐
Reddit
reddit.com › r/learnprogramming › [java] how to get around using instanceof?
r/learnprogramming on Reddit: [Java] How to get around using instanceof?
November 15, 2016 -

I may need to redesign a portion of a project I'm working on. I've read that it's generally bad practice to use the instanceof operator, and the only solution I have seen that gets around it is the visitor design pattern, which seems unnecessarily complicated. Situation:

I have a collection of Job objects. Each Job has 4 lists of various tasks that are read in at runtime during the Job creation. The tasks share a common interface, and there are 4 flavors of Task. For simplicity, I'm using TaskType1, TaskType2, etc.

The Job class has the following methods that add the tasks to the appropriate list:

void addTaskType1(TaskType1 task){
    taskType1List.add(task);
}

There is one method for each type of task. I have a TaskFactory which returns the appropriate task type during Job creation. So, my parsing object reads a task, sends the type description to the factory, which returns the appropriate type of Task.

What I currently have to do to add the Task to the correct list is as follows:

Task returnedTask = taskFactory.createTask(taskType);
if(returnedTask instance of TaskType1){
    job.addTaskType1(returnedTask);
}
else if(returnedTask instanceof TaskType2) and so on ....

Is there a better approach? It feels wrong to do it this way.

There was a similar question posted here before that said having multiple lists was probably the wrong way to approach the problem, but I haven't been able to locate that post for more suggestions. Thanks for any help.

🌐
OpenJDK
openjdk.org › jeps › 394
JEP 394: Pattern Matching for instanceof
July 27, 2020 - Make it a compile-time error for a pattern instanceof expression to compare an expression of type S against a pattern of type T, where S is a subtype of T. (This instanceof expression will always succeed and is then pointless. The opposite case, where a pattern match will always fail, is already a compile-time error.) Other refinements may be incorporated based on further feedback. Nearly every program includes some sort of logic that combines testing if an expression has a certain type or structure, and then conditionally extracting components of its state for further processing. For example, all Java programmers are familiar with the instanceof-and-cast idiom:
🌐
OpenJDK
openjdk.org › jeps › 305
JEP 305: Pattern Matching for instanceof (Preview)
Enhance the Java programming language with pattern matching for the instanceof operator. Pattern matching allows common logic in a program, namely the conditional extraction of components from objects, to be expressed more concisely and safely.
🌐
IONOS
ionos.com › digital guide › websites › web development › java instanceof operator
How the Java instanceof operator works
October 22, 2024 - When you use instanceof in Java, the operator compares a reference variable with a specific class that is also specified by the user. It doesn’t include any ad­di­tion­al in­for­ma­tion about the nature of the object or the class.
🌐
Reddit
reddit.com › r/learnjava › how do i use `instanceof`? doing `a instanceof b` gives me an incompatible types error, not a boolean
How do I use `instanceof`? Doing `a instanceof b` gives me ...
January 28, 2019 -

For example, I have an arrayList called a and a String called b

Typing boolean x = a instanceof String; just gives an error that says java: incompatible types: ArrayList cannot be converted to String...am I using this incorrectly somehow?

🌐
Coderanch
coderanch.com › t › 730270 › java › Checking-instanceof-List
Checking instanceof on a List<T> (Java in General forum at Coderanch)
May 10, 2020 - That means that instanceof simply is unable to check that a List is a List<Voice>. You have two options: 1) Ignore (and preferably suppress) the warning. 2) Loop through the entire List, check that every element is an instance of Voice, then ignore (and preferably suppress) the warning.