How does instanceof work in Java, and what exactly does it test?
The operator instanceof is a type test. It asks whether the object on the left is an instance of the type on the right, and it gives you true or false.
The word "instance" matters, because the test is not about the exact class. It is true when the object is of that class, and it is also true when the object is of a class that extends that class. So a Dog is an Animal, and a Puppy is a Dog as well.
It works with interfaces too, because a class can implement an interface without extending anything. That is the usual way to ask whether an object supports a particular behaviour.
public class Main {
public static void main(String[] args) {
describe("hello");
describe(42);
describe(new int[] {1, 2, 3});
// A null value is not an instance of anything.
String missing = null;
System.out.println("null instanceof String : " + (missing instanceof String));
}
static void describe(Object value) {
if (value instanceof String) {
String text = (String) value;
System.out.println("a string of length " + text.length());
} else if (value instanceof Integer) {
Integer number = (Integer) value;
System.out.println("a number " + number);
} else if (value instanceof int[]) {
int[] numbers = (int[]) value;
System.out.println("an array of length " + numbers.length);
} else {
System.out.println("something else");
}
}
}
So the answer to the question is this. It tests whether the object is of that type or of a type that comes from it, it works with classes and with interfaces, and it gives false for a null value.
The next question in this topic looks at how to use it safely.