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.
if (shape instanceof Circle c) { System.out.println(c.radius()); }
Try it
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.
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
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
nullis never an instance.null instanceof Objectisfalse.- 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, thethenbranch, and the code after anif (!(o instanceof T t)) return;. It is not available in||right sides or theelsebranch. - Reifiable types. You can test against
List<?>but notList<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
instanceofare a later preview feature in newer JDKs; stick to reference types in production code. - Design. Long
instanceofchains are a smell. Consider polymorphism, a sealed hierarchy with aswitchpattern, or a visitor.