instanceof
Checks whether an object is an instance of a type and binds a variable of that type.
Available since: Java 1.0
Syntax
value instanceof Type nameExamples
A check that declares a variable (pattern matching, Java 16):
void main() {
Object value = "hello";
if (value instanceof String s) {
IO.println(s.toUpperCase());
}
}Output:
HELLOThe variable is also usable after &&; for null the result is false:
void main() {
Object[] values = {42, "text", -7, null};
for (Object v : values) {
if (v instanceof Integer n && n > 0) {
IO.println("positive: " + n);
}
}
IO.println(null instanceof Object);
}Output:
positive: 42
falseNotes
Before, you wrote a check and a separate cast: if (o instanceof String) { String s = (String) o; ... }. The form with a variable does the same in less code. When there are many cases, a switch with type patterns reads better.
See also
- switch — Picks a branch by value; as an expression it returns a result.
- Object.getClass() — Returns the runtime class of an object.
- sealed / permits — Restricts which classes may extend a class or implement an interface.
Related recipes
In the tutorial
- Patterns in instanceof — Pattern matching for instanceof in Java — a type check and a cast in one line, the scope of a pattern variable and negation.