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.
if (obj instanceof String s && s.length() > 3) { System.out.println(s.toUpperCase()); }
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 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 theif. &&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 notList<String>, since type arguments are erased. A cast fromObjecttoList<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, whileinstanceofaccepts subclasses. Choose deliberately inequals(). - Design smell: long chains of
instanceofoften mean you want polymorphism, or a sealed type with a patternswitch. - Reflection variants:
Class.isInstance(obj)is the dynamic version of this operator. - Arrays:
obj instanceof int[]andobj instanceof String[]both work.
Related
switch,record,sealed,class- Lessons: Pattern matching, Polymorphism, Type casting