Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท Operators

The Java instanceof operator

Reference for the Java instanceof operator: type tests, null behavior, pattern matching with binding variables (Java 16), scope rules and generics.

instanceof tests whether the object a reference points to is an instance of a given type. It produces a boolean. For null it always produces false, so it doubles as a null check.

Since Java 16 the operator also supports a type pattern: obj instanceof String s tests the type and, if the test succeeds, declares a variable s that is already cast. This removes the repetitive cast after the test.

Java
if (shape instanceof Circle c) {
    System.out.println(c.radius());
}

Try it

Java Type test and pattern variable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java Scope, negation and record patterns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Syntax

Java
expression instanceof Type
expression instanceof Type identifier        // type pattern, Java 16
expression instanceof RecordType(pattern, ...) // record pattern, Java 21
Part Description
expression A reference expression (any non-primitive type)
Type A class, interface, array or generic type that the expression's type can be cast to
identifier A new local variable, assigned only when the test succeeds

Usage notes

  • null is never an instance. null instanceof Object is false.
  • Compile-time check. If the cast could never succeed, such as "a" instanceof Integer, the code does not compile.
  • Binding scope is flow-based: it covers the && right side, the then branch, and the code after an if (!(o instanceof T t)) return;. It is not available in || right sides or the else branch.
  • Reifiable types. You can test against List<?> but not List<String> unless the compiler can prove it; type arguments are erased.
  • Record patterns (Java 21) deconstruct a record in one step and nest.
  • Primitive patterns in instanceof are a later preview feature in newer JDKs; stick to reference types in production code.
  • Design. Long instanceof chains are a smell. Consider polymorphism, a sealed hierarchy with a switch pattern, or a visitor.