Sub topic 2
Why check-then-cast is awkward
This chapter assumes you know basic Java syntax, inheritance, reference casts, Boolean operators, and the instanceof operator. A cast is an operation that tells Java to treat a reference as a more specific type.
The traditional idiom
Suppose a method receives an Object. You want to use it as a String only when it really refers to a string. The traditional code first tests the type and then casts the value:
public class CheckThenCastDemo {
public static void main(String[] args) {
Object value = "hello";
if (value instanceof String) {
String text = (String) value;
System.out.println(text.length());
}
}
}The instanceof expression asks whether the object has the requested runtime type. The cast converts the reference so the compiler allows String operations such as length().
The same type appears twice:
Stringappears in the type test.Stringappears again in the cast.textmust be declared separately inside theifblock.
This repetition is harmless in a small example, but it creates extra places for code to become inconsistent.
The duplicated steps
The type test and cast express one idea: “If this value is a String, use it as a String.” Java's older syntax makes that idea appear as two separate operations.
flowchart TD
A[Receive an Object] --> B[Test with instanceof]
B -->|true| C[Cast with String]
C --> D[Declare a String variable]
D --> E[Use String methods]
B -->|false| F[Skip the block]The cast is usually safe when it immediately follows a test of the same stable variable. However, the compiler does not connect the two operations as one declaration. Changes between them can cause a failure:
public class ChangedValueDemo {
public static void main(String[] args) {
Object value = "hello";
if (value instanceof String) {
value = 42;
String text = (String) value;
System.out.println(text);
}
}
}This program compiles, but it throws ClassCastException when it runs. The test succeeded for the original value. The variable was then reassigned before the cast.
A similar problem can occur when code repeats a method call instead of storing its result. If the method can return different objects, the value tested might not be the value cast. Storing the result in a local variable avoids that specific problem, but the check and cast are still separate.
What the newer syntax improves
Pattern matching for instanceof combines the test, cast, and variable declaration:
public class PatternPreview {
public static void main(String[] args) {
Object value = "hello";
if (value instanceof String text) {
System.out.println(text.length());
}
}
}Here, String text is a type pattern. If the pattern matches, Java creates text as a reference whose compile-time type is String. The code states the intent once and removes the manual cast.
The variable introduced by a type pattern is called a binding variable. Later chapters examine exactly where that variable is available and how Boolean conditions affect its scope.
A practical comparison
| Traditional form | Pattern form |
|---|---|
| Tests and casts separately | Tests and binds in one expression |
| Repeats the type name | Names the type once |
| Requires a manual cast | Compiler provides the typed variable |
| Easier to separate accidentally | Keeps the operation together |
Exercise
Why can the cast in ChangedValueDemo throw ClassCastException even though the instanceof test succeeded?
Show answer
The variable was reassigned after the test. The test matched the original String, but the cast examined the new Integer value.