Sub topic 1
Java Pattern Matching for `instanceof`
Prerequisites
This chapter assumes you know basic Java syntax, classes, inheritance, reference casts, Boolean operators, and the equals method. You should also know that a variable declared with a parent type can refer to an object created from a child type.
What `instanceof` Tests
The instanceof operator tests whether an object is an instance of a specified type. It returns a boolean: true when the object can be treated as that type, and false otherwise.
public class InstanceofDemo {
public static void main(String[] args) {
Object value = "hello";
System.out.println(value instanceof String);
System.out.println(value instanceof Integer);
}
}The object stored in value is a String, so the first expression prints true. The second prints false.
The test uses the object's runtime type, which is the type of the object that exists while the program runs. It does not use only the variable's declared type. Although value is declared as Object, its actual object is a String.
instanceof also respects inheritance. If Dog extends Animal, then a Dog object is also an Animal object. A test for Animal can therefore succeed for a Dog.
flowchart TD
A["Object reference"] --> B{"instanceof String?"}
B -->|yes| C["The object can be used as String"]
B -->|no| D["The object is not usable as String"]The test does not change the variable's declared type. After this code, value is still declared as Object:
Object value = "hello";
if (value instanceof String) {
System.out.println(value);
}Inside the block, the compiler still sees value as Object. You can call methods declared by Object, but not methods specific to String without a cast.
The Traditional Check and Cast
A cast is an explicit request to treat a reference as another compatible type. The traditional form repeats the type name:
Object value = "hello";
if (value instanceof String) {
String text = (String) value;
System.out.println(text.length());
}The instanceof test protects the cast. If the test succeeds, the cast is safe for that object. If you cast an incompatible object without testing it first, Java throws ClassCastException at runtime.
The check and cast are related but separate operations. This separation creates repeated code and gives the programmer another variable declaration to maintain. Pattern matching for instanceof, covered next, combines these operations.
Important Edge Cases
instanceof returns false when its left operand is null. A null reference does not refer to an object, so it cannot be an instance of any reference type.
public class NullInstanceofDemo {
public static void main(String[] args) {
Object value = null;
System.out.println(value instanceof String);
}
}This program prints false. It does not throw a NullPointerException.
The expression on the left must be a reference value. Primitive values such as int cannot be used directly with instanceof. The tested type must also be compatible with the expression's possible runtime types. The compiler rejects tests that can never succeed, such as testing a final unrelated class against another final unrelated class.
A type test is useful when a variable may refer to objects from several classes:
static String describe(Object value) {
if (value instanceof String) {
return "text";
}
if (value instanceof Integer) {
return "whole number";
}
return "other";
}In the next section, the type test will also declare a variable for the successful case.
Exercise
What does null instanceof String evaluate to, and why?
Show answer
It evaluates to false because null does not refer to an object, so it cannot be an instance of String.