Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

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 name

Examples

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:

HELLO

The 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
false

Notes

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.

Thanks for reading!

Donate to the site — we work hard for you.