What does the instanceof operator do in Java, and what type of value does it produce?
answer
- Type-test operator → returns boolean
- true for exact type, subclass, or interface implementation
- Checks runtime type, not declared type
- Used before a cast to avoid ClassCastException
- Left side must be a reference, not a primitive
basics
~10 sinstanceof checks whether an object is an instance of a given type (class or interface). It returns a boolean: true if the object's type matches that type or a subtype, otherwise false.
solid answer
~40 sinstanceof is a binary type-test operator: `obj instanceof Type`. It evaluates to a boolean that is true when the runtime object referred to by `obj` is an instance of `Type`, a subclass of it, or a class implementing it (if `Type` is an interface). It's most often used before a cast to avoid a ClassCastException, letting you safely narrow a reference to a more specific type. The left side must be a reference (not a primitive), and the test is on the runtime type, not the compile-time declared type. A common pattern is `if (x instanceof String) { String s = (String) x; ... }`. Since Java 16, pattern matching lets you bind the cast variable in one step: `if (x instanceof String s)`.
code
java · 9 linesObject o = "hello";
if (o instanceof String) {
String s = (String) o; // safe: instanceof confirmed the type
System.out.println(s.length()); // 5
}
Number n = 42; // autoboxed to Integer
System.out.println(n instanceof Integer); // true (subtype/impl)
System.out.println(n instanceof Double); // falsego deeper
State that instanceof tests an object's type and returns a boolean, and show the test-then-cast pattern.
Explain runtime vs declared type, subtype/interface matching, and that an impossible test is a compile error, not false.
Contrast it with pattern matching binding, discuss when to prefer polymorphism over instanceof chains, and the compile-time reachability check.
Frame instanceof usage as a design smell vs. legitimate (e.g. equals, deserialization boundaries); reason about open/closed principle and sealed-type exhaustiveness.
## What `instanceof` is `instanceof` is an **operator** in Java — a built-in symbol the language understands, like `+` or `==`. Specifically it is a **type-test operator**: it asks the question "is this object an instance of this type?" and gives back a `boolean` (`true` or `false`). The syntax is: ``` reference instanceof Type ``` - **reference** is a variable (or expression) whose value is an *object reference* — i.e. it points to an object on the heap, or is `null`. - **Type** is a class name (like `String`) or an interface name (like `Comparable`). ## Key terms defined - **Object**: a thing created with `new` (or a literal like `"hi"`) that lives in memory. - **Class**: the blueprint for objects (e.g. `String`). - **Interface**: a contract of methods a class can promise to implement (e.g. `Comparable`). - **Runtime type** vs **compile-time (declared) type**: A variable is declared with a type the compiler sees, e.g. `Object x = "hello";` — the *declared* type is `Object`, but at run time `x` actually points to a `String`. `instanceof` checks the **runtime** type, so `x instanceof String` is `true` here. - **Subtype / supertype**: If `Dog extends Animal`, then `Dog` is a subtype of `Animal`. `instanceof` returns `true` not only for the exact type but for any subtype. So a `Dog` object `instanceof Animal` is `true`. ## What it returns Always a `boolean`. It returns `true` when the object's runtime type **is**, **extends**, or **implements** the named type. Otherwise `false`. ## Why it exists Java is statically typed, but sometimes you hold a reference of a general type (`Object`, or a base class) and need to find out, at run time, what it really is — usually so you can safely **cast** it (convert the reference to a more specific type). A cast to the wrong type throws a `ClassCastException`. Testing first with `instanceof` prevents that: ```java Object o = getSomething(); if (o instanceof String) { // safe check String s = (String) o; // safe cast System.out.println(s.length()); } ``` ## Restrictions - The left operand must be a **reference type** (object), never a primitive like `int` or `boolean`. `5 instanceof Integer` does not compile. - The right operand must be a real type. If the compiler can already prove the test can never be `true` (e.g. testing a `String` against an unrelated `Integer`), it is a **compile error**, not a `false` result. ## Modern form (Java 16+) Pattern matching for `instanceof` lets you test and bind in one step: ```java if (o instanceof String s) { // s is a String, already cast System.out.println(s.length()); } ``` This is the same test plus an automatic, safe cast into the new variable `s`.
- Does instanceof return true for subclasses, or only the exact type?For subclasses too. If Dog extends Animal, a Dog object tested with `dog instanceof Animal` returns true, because a Dog 'is an' Animal. It also returns true for interfaces the object's class implements.
- Can you use instanceof on a primitive like int?No. The left operand must be a reference (object) type. `5 instanceof Integer` does not compile. You'd need an Integer object (e.g. via autoboxing into an Object) for the test to apply.
Like checking a label on a package before opening it a certain way: instanceof reads the runtime label so you don't try to unpack it as the wrong thing (which would 'break' = ClassCastException).
saying these in an interview costs you the question
- Thinking instanceof returns the object or the type rather than a boolean
- Believing it checks the declared/compile-time type instead of the runtime type
- Thinking it returns true only for the exact class and not subclasses/interfaces
- Trying to use it on primitives