Sub topic 1
A quick recap of instanceof
This chapter reviews what instanceof does before the tutorial changes how you write it. Pattern matching builds directly on the old behavior, so the details here (null, compile-time checks, generics) come back in later chapters.
Prerequisites
This chapter assumes you already know the following:
- Basic Java syntax: classes, methods, and
staticmembers. - Inheritance and subtyping:
extends,implements, and what it means for one type to be a subtype of another. - Reference casts, such as
(String) o, and the fact that a bad cast throwsClassCastException. - The boolean operators
&&,||and!. - How to write an
equalsmethod.
You need a JDK to run the examples. The code in this chapter compiles on any version from Java 8 on, except where a note says otherwise.
What instanceof tests
instanceof is a binary operator. The left operand is an expression of reference type. The right operand is a type. The result is a boolean.
public class InstanceofRecap {
public static void main(String[] args) {
Object o = "hello";
System.out.println(o instanceof String); // true
System.out.println(o instanceof Object); // true
System.out.println(o instanceof Integer); // false
}
}The test asks whether the object the expression refers to is an instance of the named type. An object is an instance of its own class, of every superclass, and of every interface those classes implement. That is why o instanceof Object is true for every non-null reference.
The result depends on the runtime type of the object, not on the static type of the variable. Here o is declared as Object, but the object it refers to is a String, so the test against String succeeds.
Runtime type versus static type
Every reference expression has two types:
- The static type is the type the compiler knows from the declaration. For
Object o, it isObject. - The runtime type is the actual class of the object when the program runs. For
Object o = "hello", it isString.
instanceof looks at the runtime type. This is why it is useful: the compiler cannot know which subtype a variable holds, so you ask at run time.
public class Hierarchy {
interface Shape {}
static class Circle implements Shape {}
static class Square implements Shape {}
static class RoundedSquare extends Square {}
public static void main(String[] args) {
Shape s = new RoundedSquare();
System.out.println(s instanceof Shape); // true
System.out.println(s instanceof Square); // true
System.out.println(s instanceof RoundedSquare); // true
System.out.println(s instanceof Circle); // false
}
}The object is a RoundedSquare. It is also a Square (its superclass) and a Shape (the interface Square implements). It is not a Circle.
How the test is evaluated
The evaluation has two steps. The null check comes first, and the type comparison only happens for non-null values.
Null never matches
If the left operand evaluates to null, the result is false. This holds for every right-hand type, including Object.
public class NullRecap {
public static void main(String[] args) {
Object n = null;
System.out.println(n instanceof Object); // false
System.out.println(n instanceof String); // false
}
}This is a useful property. A true result guarantees two things: the reference is not null, and the object has the tested type. A cast that follows a successful test can never fail, and it can never meet a null. The same rule carries over to patterns in later chapters.
The compiler rejects impossible tests
The compiler checks that the test could possibly succeed. If the static type of the left operand and the tested type are unrelated, the code does not compile.
public class Impossible {
public static void main(String[] args) {
String s = "hello";
// Does not compile: String and Integer are unrelated classes.
// System.out.println(s instanceof Integer);
Object o = s;
System.out.println(o instanceof Integer); // compiles, prints false
}
}The rule is that the left operand's static type must be castable to the right-hand type. String cannot be cast to Integer, because neither is a subtype of the other. Object can be cast to anything, so the second test compiles.
Interfaces behave a little differently. A non-final class can be castable to an interface it does not implement, because a subclass might implement it. A final class is castable only to the interfaces it actually implements.
The test is also allowed when the static type is already a subtype of the tested type. It is then true for every non-null value. Older compilers accepted this silently, so a redundant test is a sign of dead logic.
Interfaces, arrays and raw types
The right-hand type can be a class, an interface, or an array type.
public class ArraysAndInterfaces {
public static void main(String[] args) {
Object ints = new int[3];
Object strings = new String[1];
System.out.println(ints instanceof int[]); // true
System.out.println(ints instanceof Object[]); // false
System.out.println(strings instanceof Object[]); // true
System.out.println(strings instanceof String[]); // true
System.out.println(strings instanceof Comparable); // false
}
}Arrays of primitives are not Object[], because int is not a reference type. Arrays of references are covariant. A String[] is an Object[].
Generics and the old restriction
Generic type arguments are erased at run time. A List<String> and a List<Integer> are both just List once the program runs. Before Java 16, this led to a firm rule: the type on the right of instanceof had to be reifiable. A reifiable type is one whose full type information is available at run time.
import java.util.ArrayList;
import java.util.List;
public class GenericsRecap {
public static void main(String[] args) {
Object o = new ArrayList<String>();
System.out.println(o instanceof List); // true, raw type
System.out.println(o instanceof List<?>); // true, unbounded wildcard
// Does not compile on Java 8 to 15, and still does not compile
// here because the cast from Object to List<String> is unchecked:
// System.out.println(o instanceof List<String>);
}
}The raw type List and the unbounded wildcard List<?> are reifiable. Both ask only whether the object is a list. Neither says anything about the element type.
Java 16 relaxed the rule. A parameterized type is accepted when the cast from the left operand's static type is checked, which means the compiler can prove it safe. A later chapter covers this. For now, remember that the runtime test can never inspect type arguments.
instanceof compared with getClass()
Some code uses getClass() where instanceof would do. The two differ for subclasses.
public class ExactVersusSubtype {
static class Base {}
static class Derived extends Base {}
public static void main(String[] args) {
Base b = new Derived();
System.out.println(b instanceof Base); // true
System.out.println(b.getClass() == Base.class); // false
System.out.println(b.getClass() == Derived.class); // true
}
}| Check | True for subclass instances? | Null-safe? |
|---|---|---|
| `x instanceof T` | Yes | Yes, gives false |
| `x.getClass() == T.class` | No, exact class only | No, throws `NullPointerException` |
The choice matters in equals methods. instanceof allows a subclass instance to equal a superclass instance, which can break symmetry if the subclass adds state. getClass() keeps the comparison strict but means subclasses never equal their parents. A later chapter returns to this when it covers the equals idiom.
The idiom this tutorial replaces
In practice, instanceof is nearly always followed by a cast of the same variable to the same type:
public class CheckThenCast {
public static void main(String[] args) {
Object o = "hello";
if (o instanceof String) {
String s = (String) o;
System.out.println(s.length()); // 5
}
}
}The type String is written twice, and a new variable s is declared by hand. The cast is safe only because the test came first. If someone later edits one String and not the other, the compiler may not catch the mistake. The next chapters remove this repetition by letting the test declare the variable itself.
Common mistakes to recheck
- Casting without testing first.
(String) othrowsClassCastExceptionwhenoholds anInteger. It does not throw whenois null, because a null reference casts to any reference type. - Expecting
instanceofto be true for null. It never is. - Testing against a parameterized type and expecting the type arguments to be checked. They are not.
- Using
getClass()when subtypes should match. - Writing a test that the compiler can already prove true. It is dead logic and often hides a design problem.
Exercises
Consider this program:
public class Quiz {
static class A {}
static class B extends A {}
public static void main(String[] args) {
A a = new B();
A none = null;
System.out.println(a instanceof B);
System.out.println(a instanceof A);
System.out.println(none instanceof A);
System.out.println(a.getClass() == A.class);
}
}Exercise
What does the program print, line by line, and why does each line print that value?
Show answer
It prints true, true, false, false. The object is a B, so it is an instance of B (true) and, because B extends A, also of A (true). The variable none is null, and instanceof is false for null (false). The exact class of the object is B, not A, so the getClass comparison is false.
Exercise
Why does String s = "x"; boolean b = s instanceof Integer; fail to compile, while the same test on a variable declared as Object compiles and returns false?
Show answer
The compiler requires the left operand's static type to be castable to the tested type. String cannot be cast to Integer because neither is a subtype of the other. Object can be cast to any reference type, so the test compiles and the runtime check returns false.