Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท Keywords and Statements

The instanceof operator

Reference for the Java instanceof operator: test an object's type, bind a pattern variable, use record patterns, and avoid null and generics pitfalls.

instanceof tests whether the object a reference points to is an instance of a given type. It yields true for that class, any subclass, or any implemented interface, and always false for null.

Since Java 16 the operator can also bind a variable when the test succeeds, so you do not need a separate cast. In Java 21 it works with record patterns that take a record apart.

Java
if (obj instanceof String s && s.length() > 3) {
    System.out.println(s.toUpperCase());
}

Try it

Java Type test with a 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 Record patterns and the old cast style

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 name                  // type pattern
expression instanceof RecordType(pattern, ...)   // record pattern
Part Rule
Left operand A reference expression (not a primitive, until primitive patterns, which are preview in Java 25).
Right operand A reference type. A compile error appears if the cast could never succeed.
Result boolean. false when the operand is null.
Pattern variable In scope only where the compiler can prove the match succeeded.

Usage notes

  • Scope of the variable: flow-sensitive. In if (!(o instanceof String s)) return; ... s ... the variable is available after the if.
  • && works, || does not: o instanceof String s && s.isEmpty() is fine; o instanceof String s || s.isEmpty() is rejected.
  • Generics: you can test List<?> but not List<String>, since type arguments are erased. A cast from Object to List<String> after the test is unchecked.
  • Redundant test: when the compile-time type is already the target (String s; s instanceof String t), older Java versions complain; Java 21+ allows it.
  • Equality: getClass() == other.getClass() demands the exact class, while instanceof accepts subclasses. Choose deliberately in equals().
  • Design smell: long chains of instanceof often mean you want polymorphism, or a sealed type with a pattern switch.
  • Reflection variants: Class.isInstance(obj) is the dynamic version of this operator.
  • Arrays: obj instanceof int[] and obj instanceof String[] both work.