The instanceof Operator in Java
instanceof checks whether an object is an instance of a given class or interface at runtime, evaluating to a boolean. It's the standard way to answer "what kind of object is this, really?" before doing something that only makes sense for that specific type — most often right before a cast, to make sure the cast will actually succeed instead of throwing a ClassCastException.
Since Java 16, pattern matching for instanceof lets the check and the cast happen in one expression. if (obj instanceof String s) both confirms obj is a String and immediately declares a new variable s already cast to that type, available for use inside the if block — removing the separate cast statement that used to be required afterward.
The basic check
obj instanceof SomeClass evaluates to true if obj currently refers to an object that is a SomeClass, or a subclass of it.
null is never an instance of anything
obj instanceof SomeClass is simply false whenever obj is null, so it also doubles as a safe null check.
Guarding a cast
Checking instanceof before casting avoids a runtime ClassCastException from a cast that wouldn't actually succeed.
Pattern matching for instanceof (Java 16+)
if (obj instanceof String s) checks and casts in one step, making s available as an already-typed String inside that block.
Works with interfaces too
instanceof isn't limited to classes — checking against an interface confirms the object implements it, however it's actually built underneath.
public class InstanceofDemo { public static void main(String[] args) { Object value = "hello"; if (value instanceof String s) { System.out.println("Length: " + s.length()); } System.out.println("Is Integer: " + (value instanceof Integer)); }}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself — building beats watching.