The instanceof Operator
Use instanceof to check object types before casting and avoid ClassCastException.
The instanceof Operator is a free Java Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
The instanceof Operator
The instanceof operator checks whether an object is an instance of a given type at runtime. It returns true or false and prevents ClassCastException before casting.
Basic instanceof Usage
Use instanceof to test the runtime type of an object before performing a safe cast.
Object obj = "Hello, Java!";
if (obj instanceof String) {
String s = (String) obj;
System.out.println(s.toUpperCase()); // HELLO, JAVA!
}
Object num = Integer.valueOf(42);
System.out.println(num instanceof Integer); // true
System.out.println(num instanceof String); // falseinstanceof with Inheritance
instanceof returns true if the object is an instance of the class or any subclass (or any implemented interface).
class Animal {}
class Dog extends Animal {}
class Cat extends Animal {}
Animal a = new Dog();
System.out.println(a instanceof Animal); // true
System.out.println(a instanceof Dog); // true
System.out.println(a instanceof Cat); // falsePattern Matching instanceof (Java 16+)
Java 16 introduced pattern matching for instanceof: you can declare a binding variable in the same expression, eliminating the explicit cast.
Object shape = "circle";
// Old way
if (shape instanceof String) {
String s = (String) shape;
System.out.println(s.length());
}
// New way (Java 16+) — binding variable 's' is in scope
if (shape instanceof String s) {
System.out.println(s.length()); // 6
}Pattern Matching in a Method
Pattern matching makes type-based dispatch clean and safe. The binding variable is only in scope where the condition is known to be true.
sealed interface Shape permits Circle, Rectangle {}
record Circle(double radius) implements Shape {}
record Rectangle(double width, double height) implements Shape {}
static double area(Shape s) {
if (s instanceof Circle c) {
return Math.PI * c.radius() * c.radius();
} else if (s instanceof Rectangle r) {
return r.width() * r.height();
}
throw new IllegalArgumentException("Unknown shape");
}
System.out.println(area(new Circle(5))); // 78.53...
System.out.println(area(new Rectangle(4, 6))); // 24.0instanceof with null
null instanceof AnyType always returns false — it never throws. This makes instanceof a null-safe way to check before casting.
String s = null;
System.out.println(s instanceof String); // false (not NPE)
Object o = null;
if (o instanceof Number n) {
System.out.println(n.intValue());
} else {
System.out.println("Not a number (or null)"); // prints this
}Switch Expressions and Pattern Matching
Java 21 extends pattern matching to switch expressions, allowing clean type-based routing without chained if-else.
static String describe(Object obj) {
return switch (obj) {
case Integer i -> "Integer: " + i;
case Double d -> "Double: " + d;
case String s -> "String of length " + s.length();
case null -> "null value";
default -> "Unknown: " + obj.getClass().getSimpleName();
};
}
System.out.println(describe(42)); // Integer: 42
System.out.println(describe(3.14)); // Double: 3.14
System.out.println(describe("hello")); // String of length 5
System.out.println(describe(null)); // null valueClassCastException Without instanceof
Casting without checking first leads to ClassCastException at runtime — a common bug in legacy code that pattern matching helps prevent.
Object obj = "I am a String";
try {
Integer i = (Integer) obj; // ClassCastException!
} catch (ClassCastException e) {
System.out.println("Cannot cast String to Integer");
}
// Safe version
if (obj instanceof Integer i) {
System.out.println("Is integer: " + i);
} else {
System.out.println("Not an integer");
}Practical: Processing Mixed List
A real-world use case: processing a heterogeneous list of objects using pattern matching.
import java.util.List;
List<Object> events = List.of(
"User login", 42, 3.14, "Payment processed", 100
);
double numericSum = 0;
for (Object e : events) {
if (e instanceof Integer n) numericSum += n;
else if (e instanceof Double d) numericSum += d;
else if (e instanceof String s) System.out.println("Log: " + s);
}
System.out.printf("Numeric sum: %.2f%n", numericSum); // 145.14Sealed Classes and Exhaustive Matching
Sealed classes (Java 17+) restrict which classes can extend them. Combined with pattern matching switch, the compiler can verify exhaustiveness — no default case needed.
sealed interface Notification permits EmailNotification, SmsNotification {}
record EmailNotification(String to, String body) implements Notification {}
record SmsNotification(String phone, String text) implements Notification {}
static void send(Notification n) {
switch (n) {
case EmailNotification e ->
System.out.println("Email to " + e.to() + ": " + e.body());
case SmsNotification s ->
System.out.println("SMS to " + s.phone() + ": " + s.text());
// no default needed — compiler knows all cases are covered
}
}Guarded Patterns
Pattern matching supports guards with when (Java 21) to add boolean conditions alongside type checks.
static String classify(Number n) {
return switch (n) {
case Integer i when i < 0 -> "negative int: " + i;
case Integer i when i == 0 -> "zero";
case Integer i -> "positive int: " + i;
case Double d -> "double: " + d;
default -> "other number";
};
}
System.out.println(classify(-5)); // negative int: -5
System.out.println(classify(0)); // zero
System.out.println(classify(7)); // positive int: 7Quick Check
What does the following expression return?
Object obj = null; boolean result = obj instanceof String; System.out.println(result);
Recap: instanceof Operator
Key takeaways:
- instanceof checks runtime type and prevents ClassCastException
- Returns false for null — never throws NPE
- Returns true for the class itself and all its subclasses/interfaces
- Java 16+ pattern matching: if (x instanceof String s) combines check + cast
- Java 21 switch with patterns routes cleanly by type with optional guards
- Sealed classes + exhaustive switch eliminate the need for a default case
Frequently asked questions
Is the “The instanceof Operator” lesson free?
Yes — the full text of “The instanceof Operator” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.
What will I learn in “The instanceof Operator”?
Use instanceof to check object types before casting and avoid ClassCastException. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Java Academy?
No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “The instanceof Operator” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Java Academy lesson?
Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Primitive vs Reference Types
- Widening and Narrowing Conversions
- The instanceof Operator
- Type Casting in Practice